【问题标题】:SQL in Prepared Statement throwing SQL exception准备好的语句中的 SQL 引发 SQL 异常
【发布时间】:2017-05-21 17:45:29
【问题描述】:

我试图弄清楚为什么这段代码会引发 SQL 异常。当我运行此代码时,它会打印“Bad SQL in customer insert ps”,这是该内部 catch 块中的消息。我在这个类和我的应用程序的其他地方都有多个带有 SQL 插入的准备好的语句。他们都工作正常。我一遍又一遍地查看这个,我无法弄清楚为什么这个抛出异常。

try {
                Connection conn = DBconnection.getConnection();
                PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
                System.out.println(ps.toString());
                ResultSet rs = ps.executeQuery();

                if (rs.next()) {
                    customerId = rs.getString("customerId");
                }
                try {

                    PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
                            + "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
                            + "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");

                    customerInsert.executeUpdate();

                    System.out.println(customerInsert.toString());
                    System.out.println(rs.toString());

                } catch (SQLException sq) {
                System.out.println("Bad SQL in customer insert ps");
                }

            } catch (SQLException customerIdException) {
                System.out.println("Bad SQL in customer ps");
            }

【问题讨论】:

    标签: java sql prepared-statement


    【解决方案1】:

    您使用PreparedStatement 就像您使用Statement 一样。不要把参数放在SQL里,放在占位符?标记里。然后使用各种setXyz方法(setStringsetInt等)填写参数:

    PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
        "INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
                       "VALUES(?, ?, ?, ?, ?, ?, ?);"
    );
    customerInsert.setString(1, name);
    customerInsert.setInt(2, addressId);
    // ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect
    

    【讨论】:

    • 我要试试。我在我的班级和程序的其他地方还有其他类似的陈述,这些陈述是这样设置的,它们确实有效。我不确定这里的根本问题是什么。如果我这样做并解决了我的问题,我会很高兴并单击复选标记。谢谢!我对 StackOverflow 有点陌生。
    • @aforbe2:不用担心,不用着急。如果您在问题中显示的表格中还有其他人,即使他们正在工作,更新他们以使用上面的表格也很重要,因为问题中代码的编写方式是 wide-对 SQL 注入攻击开放。我们谁都不想打这个电话:bobby-tables.com :-)
    • 哈哈,谢谢你的连环画。以后我会牢记这一点。也谢谢你的好意。我发现一些关于 SO 的开发人员可能有点棘手。我不知道为什么会抛出异常,但您的回答解决了我的问题,我正在更改所有其他语句以使用 set 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多