温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java数据库连接PreparedStatement的使用详解

发布时间:2020-08-23 05:03:01 来源:脚本之家 阅读:198 作者:嗯哼 栏目:编程语言

本文介绍了Java数据库连接PreparedStatement的使用详解,分享给大家,具体如下:

首先了解Statement和PreparedStatement的区别:

Java数据库连接PreparedStatement的使用详解

由此可见,一般使用PreparedStatement。

操作数据库SU(Course表),其中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

1. PreparedStatement可以提高执行的效率(因为它有预编译的功能)

2. PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI