jsp資料庫(一、使用jdbc連線資料庫)
阿新 • • 發佈:2018-11-03
步驟:
一、載入驅動程式
Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
二、建立連線物件
Connection conn = DriverManager.getConnection("主機名","使用者名稱","密碼");
三、建立語句物件
Statement stmt = conn.createStatement();
3.1、獲取Statement物件
可滾動與可更新的ResultSet參見可滾動與可更新的ResultSet[](https://blog.csdn.net/weixin_38420342/article/details/83277868)
3.2、預處理語句(建立PreparedStatement物件)
//有三種方法:同3.1中引數一樣 public PreparedStatement prepareStatement(String sql); public PreparedStatement prepareStatement(String sql,int resultType, int concurrency); public PreparedStatement prepareStatement(String sql, int resultType, int concurrency, int holdability);
預處理一般和佔位符一起使用
//sql語句中的?就是佔位符
String sql = "select * from student where id=? and name=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
//為佔位符設定值( 使用setXXX()方法 其中XXX為資料型別 ),並且編號從1開始
pstmt.setString(1,"001");
pstmt.setString(2,"zhangsan");
四、獲取SQL語句執行的結果
根據sql語句的不同有幾種不同的執行方法:
excuteUpdate()用於insert/delete/update或者無返回值的語句
excute()用於執行可能有多個結果集的sql語句,sql為任何sql語句.
以及最常用的excuteQuery()用於查詢sql語句
String sql = "sql語句";
ResultSet rst = stmt.excuteQuery(sql);
while(rst.next)
{
}
五、關閉建立的物件
conn.close();