ga('set', 'anonymizeIp', 1);
本文講解如何實作存取oracle資料庫。
import java.sql.*;
設定Connection為連線後產生之連線物件。
public class oracleDB {
public Connection conn = null;
}
實例化oracleDB物件後,透過此設定Connection。
//Connect func
public boolean CONNECT_ORACLE() {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
try {
Class.forName(driverName);
// Create a connection to the database
String serverName = "xx.xx.xx.xx";
String portNumber = "1521"; // fill in your database port (ex:1521)
String sid = "mysid";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "myUserName";
String password = "myPassword";
// set the connection object
conn = DriverManager.getConnection(url, username, password);
System.out.println("Database connected.");
return true;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
實作DML,這邊使用SELECT簡易示範。
透過上方connect 連線成功後,將connection參數傳入設計的指令。
這邊示範獲取table欄位後回傳ArrayList<String[]>。
範例資料庫table設計如下:
COL1 | COL2 | COL3 |
---|---|---|
test1 | aaa | bbb |
test2 | ccc | ddd |
public ArrayList SELECT_TABLE(Connection conn, String TABLENAME) throws SQLException{
Statement stmt = conn.createStatement();
String SELECT_STAT = "SELECT * FROM " + TABLENAME;
ResultSet rows = stmt.executeQuery(SELECT_STAT);
ArrayList rows_db = new ArrayList();
int count=0;
while (rows.next()) {
// Assume we have 7 columns in this table
String[] dataArr = new String[7];
String colStr = "";
count+=1;
for(int i=0;i
Statement若較為複雜,可利用下面這種方法設計。
String INSERT_STAT="INSERT INTO TABLE VALUES (?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(INSERT_STAT);
pstmt.setString(1, data[0]);
pstmt.setString(2, data[1]);
pstmt.setString(3, data[2]);
try{
pstmt.executeUpdate();
pstmt.close();
return true;
}catch(SQLException e){
System.err.println(e);
pstmt.close();
return false;
}
PreparedStatement可以先將statement架構先建好,等參數準備好後再將其填入。此種方法常用於製作動態指令。
不管是Connection或是Statement操作完畢,務必將資源釋放。
statement.close();
connection.close();