mySQL PreparedStatement与JAVA中的Statement

时间:2015-05-10 21:05:17

标签: java mysql jdbc prepared-statement

在我的程序中,我必须更新数据库中的数据。为此,我创建了一个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);

这完美无缺。但是对于一般的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); 

使用此字符串,我得到一个异常,表示该参数超出范围(3> 2)。

有没有人有想法?

2 个答案:

答案 0 :(得分:1)

Prepared语句参数仅适用于查询值而不适用于列名。由于存在SQL Injection

的风险,应避免使用字符串连接
String update = "UPDATE members SET FIELD = ? WHERE MEMBERNR = ?";

答案 1 :(得分:1)

您无法绑定列名。所以代码看起来应该是这样的(注意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);