首先了解Statement和PreparedStatement的区别:
由此可见,一般使用PreparedStatement。
操作数据库SU(Course表),其中Course属性有Cno,Cname,Cpno,Ccredit。
1 public class Demo_2 { 2 3 public static void main(String[] args) { 4 5 PreparedStatement ps=null; 6 ResultSet rs=null; 7 Connection ct=null; 8 9 try {10 //1.加载驱动11 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");12 //2.得到连接13 ct=DriverManager.getConnection("jdbc:odbc:mytest");14 //3.创建PreparedStatement15 ps=ct.prepareStatement("select * from Course where Cno=? and Cpno=?");16 17 ps.setString(1,"3"); //给第一个问号赋值18 ps.setInt(2,1);19 rs=ps.executeQuery();20 21 while(rs.next()){22 String Cno=rs.getString(1);23 String Cname=rs.getString(2);24 int Cpno=rs.getInt(3);25 int Ccredit=rs.getInt(4);26 System.out.println(Cno+" "+Cname+" "+Cpno+" "+Ccredit);27 } 28 29 //使用 PreparedStatement添加一条记录30 // ps=ct.prepareStatement("insert into Course values(?,?,?,?)");31 // ps.setString(1, "8");32 // ps.setString(2, "C++");33 // ps.setInt(3, 3);34 // ps.setInt(4, 2);35 // //执行36 // int i=ps.executeUpdate();37 // if(i==1){38 // System.out.print("添加成功");39 // }else{40 // System.out.print("添加不成功");41 // }42 43 } catch (Exception e) {44 e.printStackTrace();45 }finally{46 try {47 if(rs!=null){48 rs.close();49 }50 if(ps!=null){ 51 ps.close();52 }53 if(ct!=null){54 ct.close();55 } 56 } catch (Exception e) {57 e.printStackTrace();58 }59 } 60 }61 }
运行程序,控制台输出符合条件的数据。
最后总结如下:
* PreparedStatement 使用crud
* 1. PreparedStatement可以提高执行的效率(因为它有预编译的功能)
* 2. PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。
原标题:Java数据库连接——PreparedStatement的使用
关键词:JAVA