Java数据库连接——PreparedStatement的使用

首先了解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.创建PreparedStatement
15             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注入,但是要求?赋值的方式才可以。

转载于:https://www.cnblogs.com/cxq1126/p/7360265.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值