Android Application Development HOW-TO
如何使用 JDBC 方式在 Android App 上連線到 Oracle DB
無法在 Android App 上, 透過 JDBC 連線到 Oracle DB.
環境:
- ojdbc6.jar
- Android API 7
以下的 java code 在 Java Desktop Application 上可以連線到 Oracle DB. 但無法在 Android 中成功.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;
/**
*
* @author steven
*/
public class OJDBC {
private final static Logger log = Logger.getLogger("OJDBC");
// The connect string
//jdbc:oracle:thin:[USER/PASSWORD]@[HOST][:PORT]:SID
static final String connect_string = "jdbc:oracle:thin:@localhost:1521:orcl";
static final String query = "select * from employees";
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String tag = "OJDBC";
public Connection createConnection() {
Connection conn = null;
try {
Class.forName(DEFAULT_DRIVER);
//DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//OracleDataSource ods = new OracleDataSource();
// Get the data source object
//ods.setURL(connect_string);
log.info("Connect to db");
conn = DriverManager.getConnection(connect_string, "user", "password");
log.info(conn.toString());
//conn = ods.getConnection();
log.info("connected");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public void makeQuery(Connection conn) {
// Create a statement
java.sql.Statement stmt;
try {
// create statement
stmt = conn.createStatement();
log.info("Executing query " + query + "\n");
// Execute query
ResultSet rset = stmt.executeQuery(query);
// Print the result
while (rset.next()) {
log.info(rset.getString(1) + "\n");
}
// We're done
log.info("done.\n");
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
相關資訊: