1. 程式人生 > >JDBC 訪問資料庫的基本步驟(

JDBC 訪問資料庫的基本步驟(

(1)載入JDBC驅動: 將資料庫的JDBC驅動載入到classpath中,在基於JavaEE的Web應用實際開發過程中,通常要把目標資料庫產品的JDBC驅動複製到WEB-INF/lib下.

(2)例項化資料庫連線驅動類: 並將其註冊到DriverManager中.下面是一些主流資料庫的JDBC舉動載入註冊的程式碼(只寫出筆試常考):
//Oracle8/8i/9i 資料庫(thin 模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//SQL Server7.0/2000 資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();

//MySQL資料庫
Class.forName("com.mysql.jdbc.Driver").newInstance();
(這裡省略了DB2,Informix,Sybase,PostgreSQL這幾個資料庫)

(3)建立資料庫連線,取得Connection物件.例如:
//Oracle8/8i/9i 資料庫(thin 模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn="DriverManager.getConnection(url,user,password);

//SQL Server7.0/2000 資料庫
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="";
Connection conn="DriverManager.getConnection(url,user,password);

//MySQL 資料庫
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);

(4)建立Statement物件或PreparedStatement物件.例如:
//建立Statement 物件
Statement stmt=conn.createStatement();
//建立Preparedment 物件
String sql="select * from users where userName=? and password=?";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"liubin");


(5)執行SQL語句.例如:
//執行靜態SQL查詢
String sql="select * from users";
ResultSet rs=stmt.executeQuery(sql);
//執行動態SQL查詢
ResultSet rs = pstmt.executeQuery();
//執行insert,update,delete等語句,先定義sql
stmt.executeUpdate(sql);


(6)訪問結果記錄集ResultSet物件.例如:
while(rs.next()) {
out.println("你的第一個欄位內容為: " + rs.getString(1));
out.println("你的第二個欄位內容為: " + rs.getString(2));
}


(7)依次將ResultSet,Statement,PreparedStatement,Connection物件關閉,釋放所佔用的資源.例如:
rs.close();
stmt.close();
pstmt.close();
con.close();