zoukankan      html  css  js  c++  java
  • 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注入,但是要求?赋值的方式才可以。

  • 相关阅读:
    分布式文件系统技术选型
    .net core 与nginx笔记
    分布式场景
    c printf函数
    c 编程范式
    VS2019 卡顿,甚至卡死
    SQL Server 跨服务器查询
    递归 0到100求和
    moment js 制作倒计时 比较简单
    关于地狱回调的理解
  • 原文地址:https://www.cnblogs.com/cxq1126/p/7360265.html
Copyright © 2011-2022 走看看