項目小結-JDBC訪問資料庫的基本步驟,-jdbc訪問資料

來源:互聯網
上載者:User

項目小結-JDBC訪問資料庫的基本步驟,-jdbc訪問資料
JDBC訪問資料庫的基本步驟:


(1)將資料庫的JDBC驅動載入到classpath中,在基於javaEE的web應用實際開發過程中,
通常把目標產品的JDBC驅動複製到WEB-INF/lib中
(2)載入JDBC驅動,將其註冊到DriverManager中
//Oracle8/8i/9i(thin模式)資料庫
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//Sql server2005資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//MySQL資料庫
Class.forName("com.mysql.jdbc.Driver").newInstance();
(3)建立資料庫連接。取得Connection對象
//MySQL資料庫
String url="jdbc:mysql://localhost:3306/test?user=root&passwordroot&useUniclode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);
(4)建立Statement對象或PreparedStatement對象
Statement stat=conn.createStatement();
//建立PreparedStatement對象
String sql="select * from test where userName=? and password=? ";
PreparedStatement pstmt=conn.preparedStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"hephec");
(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());
out.println("第二個欄位"+rs.getString());
}
(7)依次將ResultSet,Statement,PreparedStatement,Connection對象關閉,釋放所佔用的資源





相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.