jdbc連線資料庫步驟(mysql、oracle、sqlserver2008)
•建立一個以JDBC連線資料庫的程式,包含7個步驟:
1、載入JDBC驅動程式:
在連線資料庫之前,首先要載入想要連線的資料庫的驅動到JVM(Java虛擬機器),
這通過java.lang.Class類的靜態方法forName(String className)實現。
2、提供JDBC連線的URL
資料庫 | Class.forName | url |
---|---|---|
sqlserver2008 | com.microsoft.jdbc.sqlserver.SQLServerDriver | jdbc:sqlserver://localhost:1433;DataBase=資料庫名稱 |
mysql | com.mysql.jdbc.Driver | jdbc:mysql://localhost:3306/資料庫名稱 |
oracle | oracle.jdbc.driver.OracleDriver | jdbc:oracle:thin:@localhost:1521:’資料庫稱’ |
3、建立資料庫的連線
•要連線資料庫,需要向java.sql.DriverManager請求並獲得Connection物件,
該物件就代表一個數據庫的連線。
•使用DriverManager的getConnectin(String url , String username ,
String password )方法傳入指定的欲連線的資料庫的路徑、資料庫的使用者名稱和
密碼來獲得。
- 以oracle為例
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");//jdbc驅動
connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:news", "scott" , "123456");
//url scott為使用者名稱 123456為密碼
System.out.println("成功");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return connection;
}
4、建立一個Statement
1、執行靜態SQL語句。通常通過Statement例項實現。
2、執行動態SQL語句。通常通過PreparedStatement例項實現。
3、執行資料庫儲存過程。通常通過CallableStatement例項實現。
具體的實現方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt =con.prepareCall("{CALL demoSp(? , ?)}") ;
5、執行SQL語句
Statement介面提供了三種執行SQL語句的方法:
executeQuery 、executeUpdate 和execute
1、ResultSet executeQuery(String sqlString):執行查詢資料庫的SQL語句 ,返回結果集(ResultSet)物件。
2、int executeUpdate(String sqlString):用於執行INSERT、UPDATE或 DELETE語句以及SQL DDL語句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用於執行返回多個結果集、多個更新計數或二者組合的 語句。
6、處理結果
• ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些 行中資料的訪問。
• 使用結果集(ResultSet)物件的訪問方法獲取資料:
while(rs.next()){
String name = rs.getString("name") ; //資料庫中欄位
String pass = rs.getString(1) ; // 此方法比較高效
}
7、關閉JDBC物件
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
if (conn != null)
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}