您好,登錄后才能下訂單哦!
本文介紹了Java數(shù)據(jù)庫連接PreparedStatement的使用詳解,分享給大家,具體如下:
首先了解Statement和PreparedStatement的區(qū)別:
由此可見,一般使用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í)有所幫助,也希望大家多多支持億速云。
免責(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)容。