简体   繁体   English

UPDATE PreparedStatement不使用JDBC更新MSSQL

[英]UPDATE PreparedStatement not updating MSSQL using JDBC

I am trying to update a MSSQL instance using JDBC using a prepared statement, I made a method to update any record in the table when given the column name, the value to update, and the updated value. 我正在尝试使用预处理语句使用JDBC更新MSSQL实例,我在给定列名,要更新的值和更新的值时创建了一个更新表中任何记录的方法。

public void updateProjectOptions(int projectID, int number, String column){
    try {
        PreparedStatement ps = conn.prepareStatement("UPDATE cryptic.dbo.projects SET ? = ? WHERE project_id = ?");
        int newNum = number+1;
        System.out.println(projectID+" "+newNum+" "+column);
        ps.setString(1, column);
        ps.setInt(2, newNum);
        ps.setInt(3, projectID);
        int debug = ps.executeUpdate();
        System.out.println("Rows affected: "+debug);
    } catch (SQLException ex) {
        Logger.getLogger(DAL.class.getName()).log(Level.SEVERE, null, ex);
    }
}

The first print statement is printing out the correct values so I know the inputs are correct, and the second print statement is letting me know that 1 row is affected which is correct. 第一个print语句打印出正确的值,因此我知道输入是正确的,第二个print语句让我知道1行是受影响的,这是正确的。

If I run the script inside of Management Studio the script runs fine and updates the table, but if I run the script from the java project nothing is updated and no errors are generated. 如果我在Management Studio中运行脚本,脚本运行正常并更新表,但是如果我从java项目运行脚本,则不会更新任何内容,也不会生成任何错误。

The db table in question has 4 columns: (int)project_id, (nvarchar)project_name, (int)num_bugs, (int)num_features 有问题的db表有4列:(int)project_id,(nvarchar)project_name,(int)num_bugs,(int)num_features

Can anyone help me out with getting this to work and/or spot whats wrong? 任何人都可以帮助我让这个工作和/或发现错误吗?

You can't bind a column name that way, only variables. 您不能以这种方式绑定列名,只能绑定变量。

I would recommend that you close that PreparedStatement in method scope in a finally block. 我建议您在finally块中关闭方法范围中的PreparedStatement Your way is asking for trouble. 你的方式是惹麻烦。

I would also call writing to System.out a very bad idea. 我也打电话给System.out写一个非常糟糕的主意。 I'd prefer returning the number of affected rows to the user. 我更愿意将受影响的行数返回给用户。

Column names cannot be parameterized in prepared statements. 列名不能在预准备语句中参数化。 You can parameterize only literal values like strings or numbers. 您只能参数化字符串或数字等文字值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM