①反射驅(qū)動(dòng),必須操作
在eclipse工程中導(dǎo)入ojdbc14.jar包
在程序中使用反射加載驅(qū)動(dòng)
Class.forName("oracle.jdbc.driver.OracleDriver");
②連接數(shù)據(jù)庫(kù)
連接一個(gè)數(shù)據(jù)庫(kù)需要一些必要的信息:
//jdbc:oracle:thin:@
//固定寫(xiě)法 1.jdbc的方式連接 2.oracle數(shù)據(jù)庫(kù) 3.連接時(shí)采用thin模式
//localhost 數(shù)據(jù)庫(kù)的網(wǎng)絡(luò)地址
//1521 數(shù)據(jù)庫(kù)的端口號(hào)
//orcl 數(shù)據(jù)庫(kù)的sid
String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";
String dbuser = "spitman"; //用戶名
String dbpassword = "123456"; //密碼
Connection connection = DriverManager.getConnection(dburl, dbuser, dbpassword);//獲取一個(gè)實(shí)例的連接
③查詢操作
//獲取一個(gè)Statement對(duì)象用于執(zhí)行sql語(yǔ)句
Statement statement = connection.createStatement();
//執(zhí)行sql語(yǔ)句//得到一個(gè)ResultSet對(duì)象
ResultSet rs = statement.executeQuery("select * from book");
④ResultSet的使用:
while(rs.next()){ //判斷ResultSet中還有沒(méi)有數(shù)據(jù)
int a = rs.getInt("列名"); //通過(guò)列名來(lái)取得數(shù)據(jù)
double b = rs.getDouble("列名"); //通過(guò)列名來(lái)取得數(shù)據(jù)
String c = rs.getString("列名");//通過(guò)列名來(lái)取得字符串?dāng)?shù)據(jù),即使是number數(shù)據(jù)也可以轉(zhuǎn)化為字符串
rs.getInt(columIndex); //通過(guò)列位數(shù)來(lái)獲取數(shù)據(jù)
rs.getString(columIndex); //同上
}
⑤釋放資源
把ResultSet / Statement /Connection 全部關(guān)閉釋放資源