This question already has an answer here:
这个问题在这里已有答案:
- JDBC PreparedStatement results in MySQL syntax error 2 answers
JDBC PreparedStatement导致MySQL语法错误2答案
In my program I have to update the data in an database. For this I created a UPDATE statement. Only the changed textfields should be updatet. Here the important part of my program:
在我的程序中,我必须更新数据库中的数据。为此,我创建了一个UPDATE语句。只应更改已更改的文本字段。这是我的计划的重要部分:
String update = "UPDATE members set " + TFArray[i].getUserData().toString() +" = \"" + TFArray[i].getText() +"\" WHERE MemberNr = " + m.getMemberNr() + ";";
System.out.println(update);
statement = DBConnection.connection.createStatement();
statement.executeUpdate(update);
DBConnection.connection.setAutoCommit(false);
DBConnection.connection.commit();
DBConnection.connection.setAutoCommit(true);
This works perfectly. But for a general UPDATE statement I wanted to use a prepared statement like that one:
这非常有效。但是对于一般的UPDATE语句,我想使用像这样的预准备语句:
String update = "UPDATE members SET ? = \" ? \" WHERE MEMBERNR = ?;";
ps = DBConnection.connection.prepareStatement(update);
ps.setString(1, TFArray[i].getUserData().toString());
ps.setString(2, TFArray[i].getText());
ps.setString(3, m.getMemberNr());
ps.addBatch();
DBConnection.connection.setAutoCommit(false);
ps.executeBatch();
DBConnection.connection.setAutoCommit(true);
With this string I get an exception which says that the parameter is out of range (3 > 2).
使用此字符串,我得到一个异常,表示参数超出范围(3> 2)。
Does anyone have an idea?
有没有人有想法?
2 个解决方案
#1
You can't bind column name. So the code should look like this (be careful about sql injection!):
您无法绑定列名称。所以代码应该是这样的(注意sql注入!):
String update = "UPDATE members SET " + TFArray[i].getUserData().toString() + " = ? WHERE MEMBERNR = ?";
ps = DBConnection.connection.prepareStatement(update);
ps.setString(1,TFArray[i].getText());
ps.setString(2,m.getMemberNr());
ps.addBatch();
DBConnection.connection.setAutoCommit(false);
ps.executeBatch();
DBConnection.connection.setAutoCommit(true);
#2
Prepared statement parameters only work for query values not column names. String concatenation should be avoided due to the risk of SQL Injection
准备好的语句参数仅适用于查询值而非列名。由于SQL注入的风险,应避免字符串连接
String update = "UPDATE members SET FIELD = ? WHERE MEMBERNR = ?";
#1
You can't bind column name. So the code should look like this (be careful about sql injection!):
您无法绑定列名称。所以代码应该是这样的(注意sql注入!):
String update = "UPDATE members SET " + TFArray[i].getUserData().toString() + " = ? WHERE MEMBERNR = ?";
ps = DBConnection.connection.prepareStatement(update);
ps.setString(1,TFArray[i].getText());
ps.setString(2,m.getMemberNr());
ps.addBatch();
DBConnection.connection.setAutoCommit(false);
ps.executeBatch();
DBConnection.connection.setAutoCommit(true);
#2
Prepared statement parameters only work for query values not column names. String concatenation should be avoided due to the risk of SQL Injection
准备好的语句参数仅适用于查询值而非列名。由于SQL注入的风险,应避免字符串连接
String update = "UPDATE members SET FIELD = ? WHERE MEMBERNR = ?";