【问题标题】:Change statement with prepared statement in Java [closed]在Java中使用准备好的语句更改语句[关闭]
【发布时间】:2021-10-13 02:21:51
【问题描述】:

我创建了使用语句插入数据库的方法。 我必须用准备好的声明来改变它。我已经阅读了文档,但我不明白。

这是我写的代码:

public void ajouterEntreprise(Entreprise e) {

    Statement stm;
    try {
        stm = cnx.createStatement();

        String query = "INSERT INTO `user`(`nom`,  `email`, `password`, `tel`,`role`,`offre`) VALUES ('" + e.getNom() + "','" + e.getEmail() + "','" + e.getPassword() + "','" + e.getTel() + " ', " + e.getRole().getId() + ",'" + e.getOffre() + "')";

        stm.executeUpdate(query);
    } catch (SQLException ex) {
        Logger.getLogger(ServiceEntreprise.class.getName()).log(Level.SEVERE, null, ex);
    }

}

【问题讨论】:

标签: java sql jdbc


【解决方案1】:

您当前的代码不安全,因为您将值连接到查询字符串中。这使您的代码容易受到 SQL 注入的攻击。为了解决这个问题,您需要切换到准备好的语句,在语句文本中使用参数占位符,然后在执行前设置语句的值。

使用准备好的语句的一个例子是(为简洁起见省略了一些列):

try (PreparedStatement pstmt = cnx.prepareStatement(
        "INSERT INTO `user`(`nom`, `email`, ...) values (?, ?, ...)")) {
    pstmt.setString(1, e.getNom());
    pstmt.setString(2, e.getEmail());
    // ...

    pstmt.executeUpdate();
}

【讨论】:

    【解决方案2】:

    你可以这样做

            String sql= "INSERT INTO `user`(`nom`,  `email`) VALUES (?,?)";
            ps = conn.PreparedStatement(sql);
            ps.setString(1, "admin");
            ps.setString(2, "123456@email.com");
            ps.executeUpdate();
    

    这是因为一般的SQL会经过多个步骤,而这里相关的两个步骤是:编译、执行。 SQL在编译阶段,会根据语法树解析生成SQL,例如

    select * from table where name = 'jhon';
    

    这条SQL会在经过一个完整的编译阶段后生成一条select语句,下例会生成两条SQL,一条是select语句,一条是delete语句。

    select * from table where name = 'jhon'; delete from table where '1' = '1'
    //will be parsed into two sql
    1.select * from table where name = 'jhon';
    2.delete from table where '1' = '1'
    

    但是都可以通过下面的SQL来填写

    select * from table where name ='%s';
    

    很明显,第一条sql是通过jhon替换%s得到的,第二条sql是通过jhon'得到的;从表中删除 '1' = '1 替换 %s

    我们用ss预编译sql会有什么不同?最值得注意的一点是sql将不再进行语法分析和编译,只进行字符串替换。比如第二条sql预编译填充后会变成

    select * from table where name = 'jhon'; delete from table where '1' = '1'
    

    约翰'; delete from table where '1' = '1 用作name的查询条件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 2012-12-18
      • 2018-09-05
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多