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