栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144863.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号