最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java数据库连接PreparedStatement的使用详解
时间:2022-06-29 01:24:34 编辑:袖梨 来源:一聚教程网
首先了解Statement和PreparedStatement的区别:
由此可见,一般使用PreparedStatement。
操作数据库SU(Course表),其中Course属性有Cno,Cname,Cpno,Ccredit。
publicclassDemo_2 { publicstaticvoidmain(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); intCpno=rs.getInt(3); intCcredit=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注入,但是要求?赋值的方式才可以。相关文章
- 诛仙2鬼王选什么种族 鬼王职业种族推荐 08-21
- 四海兄弟故乡圣埃米迪奥怎么获取 圣埃米迪奥圣徒卡获取攻略 08-21
- 原神5.8玛拉妮圣遗物怎么选 5.8玛拉妮圣遗物搭配推荐 08-21
- 光遇双星季季节任务四任务流程攻略 08-21
- 无畏契约源能行动铁壁玩法攻略 08-21
- 下一站江湖2守卫藏经阁具体位置 08-21