JDBC中的executeQuery和executeUpdate

、Me發表於2020-12-31
  • executeQuery 更新查詢資訊
 // 1.載入驅動類
 Class.forName("com.mysql.jdbc.Driver");
 //2.定義資料庫資訊
 String url = "jdbc:mysql://localhost:3306/ceshi";
 String user = "root";
 String password = "root";
 //3.建立連線
 Connection conn = DriverManager.getConnection(url,user,password);
 //4.定義sql語句
 String sql = "select * from book where bookID=?";
 //5.建立語句連線
 PreparedStatement ps = conn.prepareStatement(sql);
 int bookID = 1;
 ps.setInt(1,bookID);//查詢bookID為1的圖書資訊
 rs = ps.executeQuery();//執行executeQuery查詢
 while(rs.next()){
   System.out.println(rs.getString("stock"));
}
  • executeUpdate 更新資料操作 增刪改
// 1.載入驅動類
 Class.forName("com.mysql.jdbc.Driver");
 //2.定義資料庫資訊
 String url = "jdbc:mysql://localhost:3306/ceshi";
 String user = "root";
 String password = "root";
 //3.建立連線
 Connection conn = DriverManager.getConnection(url,user,password);
 //4.定義sql語句
 String sql = "update book set bookname=? where bookID=?";
 //5.建立語句連線
 int bookID = 1;
 String name = "王武";
 ps = conn.prepareStatement(sql);
 ps.setString(1,name);//將bookID為1的資訊中修改bookname為王武
 ps.setInt(2,bookID);
 ps.executeUpdate();

相關文章