JDBC 删除数据两种方式,PreparedStatement表示预编译的 SQL 语句的对象,防止sql注入

 1.statement使用的不方便
 2.sql注入的问题
 *  在SQL语句中使用了系统自带的关键字 or and ,让where条件判断失效
 *
  prepareStatement:
 *  1.sql语句不用在拼字符串
 *  2.防止sql注入问题

复制代码
 1 public class CURDTest {
 2     public static void main(String[] args) throws Exception {
 3         //insertTest();
 4         //deleteTest();
 5         //updateTest();
 6         //selectTest();
 7         deleteTest2();
 8     }
 9     //删除  方式2:获取预编译语句对象
10     //PreparedStatement 
11     //防止sql注入问题
12     private static void deleteTest2() throws Exception {
13         //注册驱动
14         Class.forName("com.mysql.jdbc.Driver");
15         //创建连接
16         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/day01", "root", "root");
17         //创建Statement对象
18         String sql = "delete  from stu where id =? or name =?";
19         PreparedStatement pst = conn.prepareStatement(sql);
20         pst.setInt(1,7);//(第1个?,?的内容id=6)
21         pst.setString(2, "宝贝");//(第2个?,?的内容name ="宝贝")
22         //
23         int i = pst.executeUpdate();
24         if(i!=0) {
25             System.out.println("删除成功");
26         }
27         pst.close();
28         conn.close();
29     }
30 
31     //删除
32     private static void deleteTest() throws Exception {
33         // TODO Auto-generated method stub
34         //注册驱动
35         Class.forName("com.mysql.jdbc.Driver");
36         //创建连接
37         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/day01", "root", "root");
38         //创建Statement对象
39         Statement st = conn.createStatement();
40         //  sql注入的问题
41         //     在SQL语句中使用了系统自带的关键字 or and ,让where条件判断失效
42         //String sql = "delete from stu where id= 1 or 1=1";//SQL注入问题,会把整张表的内容删除
43         String sql = "delete from stu where id= 1";
44         int i = st.executeUpdate(sql);
45         if (i!=0) {
46             System.out.println("删除成功");
47         }
48         st.close();
49         conn.close();
50     }
51 }
PreparedStatement表示预编译的 SQL 语句的对象,防止SQL注入
复制代码

 

posted @   star521  阅读(427)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示