十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂(yōu)售后,網(wǎng)站問(wèn)題一站解決
本文介紹了Java數(shù)據(jù)庫(kù)連接PreparedStatement的使用詳解,分享給大家,具體如下:
成都創(chuàng)新互聯(lián)公司主要從事成都網(wǎng)站建設(shè)、網(wǎng)站制作、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)湖濱,10余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專(zhuān)業(yè),歡迎來(lái)電咨詢(xún)建站服務(wù):028-86922220
首先了解Statement和PreparedStatement的區(qū)別:

由此可見(jiàn),一般使用PreparedStatement。
操作數(shù)據(jù)庫(kù)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ū)動(dòng)
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"); //給第一個(gè)問(wèn)號(hào)賦值
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();
}
}
}
}
運(yùn)行程序,控制臺(tái)輸出符合條件的數(shù)據(jù)。
最后總結(jié)如下:
PreparedStatement 使用crud
1. PreparedStatement可以提高執(zhí)行的效率(因?yàn)樗蓄A(yù)編譯的功能)
2. PreparedStatement可以防止sql注入,但是要求?賦值的方式才可以。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。