Java數(shù)據(jù)庫連接PreparedStatement的使用詳解
本文介紹了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í)行的效率(因為它有預編譯的功能)
2. PreparedStatement可以防止sql注入,但是要求?賦值的方式才可以。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Error:(1,?1)?java:?非法字符:?'\ufeff'問題
這篇文章主要介紹了解決Error:(1,?1)?java:?非法字符:?'\ufeff'問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11Java數(shù)據(jù)結(jié)構(gòu)之List的使用總結(jié)
List是Java中比較常用的集合類,指一系列存儲數(shù)據(jù)的接口和類,可以解決復雜的數(shù)據(jù)存儲問題,本文就來拿實際案例總結(jié)介紹一下List的使用方法,感興趣的朋友快來看看吧2021-11-11Tomcat?8.5?+mysql?5.7+jdk1.8開發(fā)JavaSE的金牌榜小項目
這篇文章主要介紹了Tomcat?8.5?+mysql?5.7+jdk1.8開發(fā)JavaSE的金牌榜小項目,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05