我有以下字符串,它包含我想要执行的查询:
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " set bodega = '" + bodega + "'"
+ " where codigo = " + codigo;我得到了一个更新语句语法错误,但我看不出哪里是错误。任何帮助都是非常感谢的。列"descripcion“和"bodega”是文本类型的列。
发布于 2012-10-21 14:52:33
嗯,这可能是因为您使用了多个set部分,而不是使用逗号分隔,也可能是因为您的codigo值没有引号(如果这是另一个字符串)……但我强烈建议您不要像这样创建SQL,直接在SQL中使用值。
取而代之的是使用预准备语句:
String sql = "UPDATE inventario set descripcion=?, bodega=? where codigo=?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, descripcion);
st.setString(2, bodega);
st.setString(3, codigo);使用预准备语句有三个直接的好处:
发布于 2012-10-21 14:51:27
删除查询中的额外SET。
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;但该查询在SQL Injection中很容易受到攻击。请参数化您的查询。例如,
String query = "UPDATE inventario" +
" set descripcion = ?, bodega = ? " +
" where codigo = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, descripcion);
prep.setString(2, bodega);
prep.setInt(3, codigo);
prep.executeUpdate();发布于 2012-10-21 14:51:23
SET关键字只需要使用一次。要更新的多个列应该用逗号分隔,如下面的语句所示。
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;顺便说一句,为了避免SQL Injection攻击,强烈建议使用PreparedStatement进行此类操作,而不是像这样构造查询。
query = "UPDATE inventario"
+ " set descripcion = ?, bodega = ? "
+ " where codigo = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, descripcion);
ps.setString(2, bodega);
ps.setInt(3, codigo);
int updateCount = ps.executeUpdate();https://stackoverflow.com/questions/12995642
复制相似问题