最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java数据库连接PreparedStatement的使用详解
时间:2022-06-29 01:24:34 编辑:袖梨 来源:一聚教程网
首先了解Statement和PreparedStatement的区别:
由此可见,一般使用PreparedStatement。
操作数据库SU(Course表),其中Course属性有Cno,Cname,Cpno,Ccredit。
publicclassDemo_2 {
publicstaticvoidmain(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);
intCpno=rs.getInt(3);
intCcredit=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
1. PreparedStatement可以提高执行的效率(因为它有预编译的功能)
2. PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。相关文章
- 致命公司铲子可攻击怪物类型汇总 12-05
- 星球重启20级头盔制作方法详解 12-05
- 星球重启分解废品任务完成方法 12-05
- 星球重启偶像任务攻略 偶像任务过法 12-05
- 星球重启9个酸液腺体获取攻略 12-05
- 星球重启采集工具制作方法 采集工具怎么做 12-05
