zoukankan      html  css  js  c++  java
  • 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注入
  • 相关阅读:
    面试题 31: 求子数组的最大和
    [面试] 结构体占用空间的问题,内存对齐~! 真的懂了,cpu取加快速度,省空间来考虑。
    [计算机] 32768~32767 计算机中的 1 表示
    C#跨线程调用窗体控件
    合并字节数组
    将汉字转化为2位大写的16进制Unicode
    关公与子龙两大杀手
    早年的J2EE笔记
    给小组新成员的一份信
    c++虚函数详解
  • 原文地址:https://www.cnblogs.com/star521/p/9011511.html
Copyright © 2011-2022 走看看