我试图用java向mysql数据库中插入一些数据,但它一直给出语法错误:
线程“main”中的异常 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;查看与您的 MySQL 服务器版本对应的手册,了解在第 1 行的“postcode ='n''附近使用的正确语法
这是我的代码:
`
public static void saveAddress(Address address) throws SQLException{
SQLConnection sql = new
SQLConnection(SQLConnection.getConnection());
if(SQLAddress.getAddressID(address) == -1){
sql.update(String.format("INSERT INTO address(houseNumber,
street, district, city, postcode) VALUES (%s ,%s ,%s ,%s
,%s)",address.getHouseNumber(),address.getStreet(),
address.getDistrict(),address.getCity(),
address.getPostCode()));
}
sql.close();
}
`
我真的不知道该怎么做,我在 mysql shell 中使用了相同的语法,它在那里工作得很好。
编辑
public static void saveAddress(Address address) throws SQLException{
Connection sql = SQLConnection.getConnection();
if(SQLAddress.getAddressID(address) == -1){
PreparedStatement ps = sql.prepareStatement("INSERT INTO address (houseNumber, street, district, city, postcode) VALUES (?, ?, ?, ?, ?);");
ps.setString(1, address.getHouseNumber());
ps.setString(2, address.getStreet());
ps.setString(3, address.getDistrict());
ps.setString(4, address.getCity());
ps.setString(5, address.getPostCode());
ps.executeUpdate();
sql.commit();
}
sql.close();
}
最佳答案
您应该为遇到此错误感到高兴,因为如果它没有发生,就会造成巨大的安全问题。将用户值插入到 SQL 字符串中启用 SQL injection attacks ,这是一种非常危险的可能性。
切换到使用 prepared statements ,并将参数绑定(bind)到它们。这类似于您对格式化所做的方式,但它是在不同的行上完成的:
PreparedStatement upd = sql.prepareStatement("INSERT INTO address(houseNumber, street, district, city, postcode) VALUES (?, ?, ?, ?, ?)");
upd.setInt(1, address.getHouseNumber());
upd.setString(2, address.getStreet());
... // Set other fields
upd.executeUpdate();
sql.commit();
关于java - 使用 java 在 ' postcode =' n' ' 附近使用的语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371489/