抛出SQL异常的Prepared Statement中的SQL

时间:2017-05-21 17:45:29

标签: java sql prepared-statement

我试图弄清楚为什么这段代码会抛出SQL异常。当我运行此代码时,它会在客户插入ps"中打印" Bad SQL,这是该内部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");
            }

1 个答案:

答案 0 :(得分: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