此方法在使用時需要將oracle的jar包加到classpath變數中,此包可以在oralce用戶端程式的$ORACLE_HOME/jdbc/lib/classes12.jar找到。
import java.sql.*;
public class jdbcthin {
//dbUrl資料庫連接串資訊,其中“1521”為連接埠,“ora9”為sid
String dbUrl = "jdbc:oracle:thin:@10.10.20.15:1521:ora9";
//theUser為資料庫使用者名稱
String theUser = "sman";
//thePw為資料庫密碼
String thePw = "sman";
//幾個資料庫變數
Connection c = null;
Statement conn;
ResultSet rs = null;
//初始化串連
public jdbcthin() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//與url指定的資料來源建立串連
c = DriverManager.getConnection(dbUrl, theUser, thePw);
//採用Statement進行查詢
conn = c.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
//執行查詢
public ResultSet executeQuery(String sql) {
rs = null;
try {
rs = conn.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void close() {
try {
conn.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ResultSet newrs;
jdbcthin newjdbc = new jdbcthin();
newrs = newjdbc.executeQuery("select * from eventtype");
try {
while (newrs.next()) {
System.out.print(newrs.getString("event_type"));
System.out.println(":"+newrs.getString("content"));
}
} catch (Exception e) {
e.printStackTrace();
}
newjdbc.close();
}
}