以下是代码:
try{
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable WHERE array=\"" + arrayName + "\"");
if(rs.next()){
String values = rs.getString("values");
if(values == null) values = "";
values += " " + added;
values = values.replaceAll("\\s+"," ");
stmt.executeUpdate("UPDATE mytable SET values = \"" + values + "\" WHERE array = \"" + arrayName + "\"");
return true;
}else{
System.out.println("Missing array '" + arrayName + "', returning false");
return false;
}
} catch(SQLException e) {
String error = "MySQL crash while adding to array " + arrayName + "\n";
error += e.getMessage();
System.out.println(error);
return false;
}
注意参数:" mytable"是我的数据库中表的名称,"添加"是我希望添加到"值"中的字符串的字符串。 mytable的列," arrayName"是已经存储在"数组中的字符串" mytable的列("数组"和"值"是唯一的列)。这是我得到的错误:
MySQL crash while adding to array anodematerialsoptions
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 'values = "item1 item2 item3 added" WHERE array = "arrayName"' at line 1
所以" stmt.executeQuery"工作正常," stmt.executeUpdate"语法错误失败。有人能指出这里有什么问题吗?
答案 0 :(得分:1)
values
是几乎 ANY sql数据库中的保留字。你必须逃脱它:
stmt.executeUpdate("UPDATE mytable SET `values` = \"" etc...
^------^---note the backticks
请注意,您很容易受到sql injection attacks的攻击。</ p>
答案 1 :(得分:0)
您可以在mysql中使用带别名的查询
变化
stmt.executeUpdate("UPDATE mytable SET values = \"" + values + "\" WHERE array = \"" + arrayName + "\"");
到
stmt.executeUpdate("UPDATE mytable t SET t.values = \"" + values + "\" WHERE t.array = \"" + arrayName + "\"");