溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java數(shù)據(jù)庫連接PreparedStatement的使用詳解

發(fā)布時間:2020-08-23 05:03:01 來源:腳本之家 閱讀:232 作者:嗯哼 欄目:編程語言

本文介紹了Java數(shù)據(jù)庫連接PreparedStatement的使用詳解,分享給大家,具體如下:

首先了解Statement和PreparedStatement的區(qū)別:

Java數(shù)據(jù)庫連接PreparedStatement的使用詳解

由此可見,一般使用PreparedStatement。

操作數(shù)據(jù)庫SU(Course表),其中Course屬性有Cno,Cname,Cpno,Ccredit。

public class Demo_2 {

  public static void main(String[] args) {

    PreparedStatement ps=null;
    ResultSet rs=null;
    Connection ct=null;

    try {
      //1.加載驅(qū)動
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      //2.得到連接
      ct=DriverManager.getConnection("jdbc:odbc:mytest");
      //3.創(chuàng)建PreparedStatement
      ps=ct.prepareStatement("select * from Course where Cno=? and Cpno=?");
      
      ps.setString(1,"3");       //給第一個問號賦值
      ps.setInt(2,1);
      rs=ps.executeQuery();
      
      while(rs.next()){
        String Cno=rs.getString(1);
        String Cname=rs.getString(2);
        int Cpno=rs.getInt(3);
        int Ccredit=rs.getInt(4);
        System.out.println(Cno+" "+Cname+" "+Cpno+" "+Ccredit);
      }  
      
      //使用 PreparedStatement添加一條記錄
//      ps=ct.prepareStatement("insert into Course values(?,?,?,?)");
//      ps.setString(1, "8");
//      ps.setString(2, "C++");
//      ps.setInt(3, 3);
//      ps.setInt(4, 2);
//      //執(zhí)行
//      int i=ps.executeUpdate();
//      if(i==1){
//        System.out.print("添加成功");
//      }else{
//        System.out.print("添加不成功");
//      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }finally{
        try {
          if(rs!=null){
            rs.close();
          }
          if(ps!=null){ 
            ps.close();
          }
          if(ct!=null){
            ct.close();
          }  
        } catch (Exception e) {
          e.printStackTrace();
        }
    }  
  }
}

運行程序,控制臺輸出符合條件的數(shù)據(jù)。

最后總結(jié)如下:

PreparedStatement 使用crud

1. PreparedStatement可以提高執(zhí)行的效率(因為它有預(yù)編譯的功能)

2. PreparedStatement可以防止sql注入,但是要求?賦值的方式才可以。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI