我有一个简单的准备语句来更新 MySQL 数据库中的记录。表、列、目标属性和信息取自文本字段。首先,我没有准备好的语句,但如果用户选择插入引号或 %%$&^* 其他符号,程序很容易崩溃。
现在我得到这个:
UPDATE client SET 'full_name'=Martinajh WHERE id='5'com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''selectedTable2' SET 'namec' = 'cellValue' WHERE id== 5' at line 1
String cellValue3 = String.valueOf( table.getValueAt(row, 0) );
int id = Integer.parseInt(cellValue3);
String selectedTable2 = (String) listOfTablesNames.getSelectedValue();
String cellValue = String.valueOf( table.getValueAt(row, column) );
String namec = table.getColumnName(column);
String query ="UPDATE ? SET ? = ? WHERE id== ?";
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(query);
preparedStmt.setString (1, "selectedTable2");
preparedStmt.setString(2, "namec");
preparedStmt.setString(3, "cellValue");
preparedStmt.setInt(4, id);
preparedStmt.executeUpdate();
最佳答案
您不能构造一个以表名作为参数的准备语句。您需要使用 String.format 的字符串连接/占位符构造 SQL。准备好的语句用于列值而不是表名。 在你的情况下:
String query ="UPDATE `" + selectedTableVar + "` SET `" + fieldNameVar + "` = ? WHERE id = ?";
//...
preparedStmt.setString(1, "cellValue");
preparedStmt.setInt(2, id);
另外,id = ?
作为@C。提到了黑灵。
至于清理 selectedTableVar
和 fieldNameVar
变量,我现在找不到链接,但是您可以自己研究什么是有效限定符MySQL ... AFAIK,任何 UTF 字符都是有效的,大多数特殊符号可能是有效表名等的一部分。使用上面建议的语法,您应该不厌其烦地不允许使用 ` 字符来防止注入(inject),我想就是这样。但必须对其进行调查。
关于java - 准备语句中的Mysql语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240979/