我试图找出这段代码抛出 SQL 异常的原因。当我运行此代码时,它会打印“Bad SQL in customer insert ps”,这是内部 catch block 中的消息。我在这个类以及我的应用程序的其他地方都有多个带有 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
,就像使用 Statement
一样。不要将参数放在 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
关于java - 准备好的语句中的 SQL 抛出 SQL 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44099957/