首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对PreparedStatement变量是否有限制或对它们的位置有要求?

问对PreparedStatement变量是否有限制或对它们的位置有要求?
EN

Stack Overflow用户
提问于 2015-11-27 07:05:40
回答 2查看 942关注 0票数 0

PreparedStatement变量(?)有限制吗?或者对他们的位置有什么要求?

我有一个方法,它接受参数来完成PreparedStatement,但是它抛出了一个SQLException。

下面是我想要使用的PreparedStatement:

代码语言:javascript
复制
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";

当我添加第一个和第二个变量时,它运行得很好。下面是工作PreparedStatement:

代码语言:javascript
复制
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";

是不是有什么原因让第一条语句不能工作?

整个方法:

代码语言:javascript
复制
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();
    }
}
EN

回答 2

Stack Overflow用户

发布于 2015-11-27 07:08:56

您不能像这样使用查询。

代码语言:javascript
复制
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";

您应该编写table的名称和column的名称,如下所示。

代码语言:javascript
复制
 String update = "UPDATE table SET column_name = ? WHERE UserID = ?";
票数 0
EN

Stack Overflow用户

发布于 2015-11-27 07:10:26

在预准备语句中,变量只能用作SQL语句中文字的占位符。因此不能将它们用作列名或表名。对于这些,您应该求助于动态SQL语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33948210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档