Java数据库连接PreparedStatement的使用详解
2022/2/8 2:13:17
本文主要是介绍Java数据库连接PreparedStatement的使用详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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
- PreparedStatement可以提高执行的效率(因为它有预编译的功能)
后总结如下:**
PreparedStatement 使用crud
-
PreparedStatement可以提高执行的效率(因为它有预编译的功能)
-
PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。
这篇关于Java数据库连接PreparedStatement的使用详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南
- 2024-09-30Dnd-Kit学习:新手快速入门指南