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