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注入
  • 相关阅读:
    怎么查看这个历史最大连接session数
    16G 手机清理
    维骨力Glucosamine的最关键的几点...
    转 OGG Troubleshooting-Database error 1 (ORA-00001: unique constraint ...)
    Steps to Resolve the Database JAVAVM Component if it Becomes INVALID After Applying an OJVM Patch
    数据库sql 使用 lag 和OVER 函数和 like 使用 小技巧
    log file sync
    转 多个版本的数据库在同一服务器上ORA-12557
    datapatch meet ORA-01422
    运维题目(七)
  • 原文地址:https://www.cnblogs.com/star521/p/9011511.html
Copyright © 2011-2022 走看看