源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-10-26 16:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java数据库连接PreparedStatement的使用详解
本文介绍了Java数据库连接PreparedStatement的使用详解,分享给大家,具体如下: 首先了解Statement和PreparedStatement的区别: [img]http://files.jb51.net/file_images/article/201708/201781582727311.png?201771582751[/img] 由此可见,一般使用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();
        }
    }  
  }
}

运行程序,控制台输出符合条件的数据。 [b]最后总结如下:[/b] PreparedStatement 使用crud 1. PreparedStatement可以提高执行的效率(因为它有预编译的功能) 2. PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部