PreparedStatement使用详解
本文详细解析Java数据库连接中PreparedStatement接口的具体应用方法,供读者参考学习。
在深入使用前,需明确Statement与PreparedStatement之间的主要差异。

基于上述对比分析,在实际开发中通常推荐优先选用PreparedStatement。
以操作数据库中的SU(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.加载驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//2.得到连接
ct=DriverManager.getConnection("jdbc:odbc:mytest");
//3.创建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);
// //执行
// 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();
}
}
}
}
执行程序后,控制台将输出符合查询条件的数据结果。
对前述内容进行归纳总结。
演示PreparedStatement在增删改查(CRUD)操作中的实际应用。
第一,PreparedStatement能够提升执行效率,这得益于其内部的预编译机制。
第二,PreparedStatement可有效防范SQL注入攻击,但前提是必须采用参数赋值的方式进行调用。
以上内容涵盖了PreparedStatement的核心知识点,希望能为读者的学习提供助力,欢迎继续支持本站。