Java 准备语句中的SQL引发SQL异常

Java 准备语句中的SQL引发SQL异常,java,sql,prepared-statement,Java,Sql,Prepared Statement,我正在试图弄清楚为什么这段代码会抛出SQL异常。当我运行这段代码时,它会打印“customer insert ps中的坏SQL”,这是内部catch块中的消息。在这个类和我的应用程序的其他地方,我已经准备了多个SQL插入语句。他们都很好。我已经一遍又一遍地查看了这个,我不明白为什么这个会抛出异常 try { Connection conn = DBconnection.getConnection(); PreparedStateme

我正在试图弄清楚为什么这段代码会抛出SQL异常。当我运行这段代码时,它会打印“customer insert ps中的坏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");
            }

您使用的是
PreparedStatement
,就像您使用的是
语句一样。不要将参数放在SQL中,而是放在占位符
标记中。然后使用各种
setXyz
方法(
setString
setInt
等)填写参数:

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:不用担心,不用着急。如果您的问题中显示的表单中有其他人,即使他们正在工作,也必须更新他们以使用上面的表单,因为问题中的代码编写方式极易受到SQL注入攻击。我们都不想打这个电话:-)哈哈,谢谢你的连环漫画。我以后会记住这一点。也谢谢你的好意。我已经找到一些开发人员,所以可能有点棘手。我不知道为什么会抛出异常,但您的回答解决了我的问题,我正在更改所有其他语句以使用set方法。