PreparedStatement变量(?)或它们的位置要求是否有限制?PreparedStatement变量或它们的位置要求是否有限制?
我有一个方法需要参数来完成一个PreparedStatement,但是,它会抛出一个SQLException。
这里是我想使用PreparedStatement:
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
当我在第一和第二变量添加它运行得很好。这里是工作PreparedStatement:
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";
是否有一个原因,我不能让第一个声明工作?
整个方法:
public static void runUpdate(String givenID, String givenAttribute, String givenUpdate) throws SQLException
{
// Establish the connection with the database
Connection conn = SimpleDataSource.getConnection();
try
{
// Create a string with the SQL Update statement
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
// Make a Prepared Statement with the connection to the database
PreparedStatement stat = conn.prepareStatement(update);
try
{
// Set the statement with the given parameters
stat.setString(1, Utility.getType(givenID));
stat.setString(2, givenAttribute);
stat.setString(2, givenUpdate);
stat.setString(3, givenID);
// Execute the Update Statement
stat.executeUpdate();
}
finally
{
// Close the prepared Statement
stat.close();
}
}
finally
{
// Close the connection to the database
conn.close();
}
}
您不能对表/列名称使用查询参数。想要这样做通常表明你有一个很差(非标准化)的模式(或正在编写一个ORM)。 –
如果您担心SQL注入,那么这意味着您从用户那里获取表和数据库名称,无论如何,这可能是一个非常糟糕的主意。如果您没有从用户那里获取表名,那么在字符串连接中没有注入风险。如果您想确定,请创建一个包含列入白名单的表名称的HashSet。 – Cruncher
表名是根据userId找到的,列是作为参数给出的。我有许多“get”方法,并试图限制冗余代码的数量。 – Moose