SQL查询将值视为列名

时间:2017-09-18 19:10:03

标签: java sql

我正在尝试建立与数据库的连接,然后运行INSERT INTO查询,但是当代码运行时,我收到错误:com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'BLUE'.

正如您在下面的代码中所看到的,我给了" BLUE"作为值而不是列名称。有谁知道我做错了什么?附: color是一个Enum,所有其他值都是双倍的。

String query = "INSERT INTO [oval] " +
               "(anchorX, anchorY, width, height, weight, color) VALUES " +
               "(" + drawingItem.getAnchor().getX() +
               ", " + drawingItem.getAnchor().getY() +
               ", " + drawingItem.getWidth() +
               ", " + drawingItem.getHeight() +
               ", " + ((Oval) drawingItem).getWeight() +
               ", " + drawingItem.getColor().toString() + ")";

initConnection();
Statement myStmt = con.createStatement();
rowsAffected = myStmt.executeUpdate(query);
closeConnection();

编辑答案:

String query = "INSERT INTO [oval] VALUES (?,?,?,?,?,?)";

initConnection();
PreparedStatement myPrepStmt = con.prepareStatement(query);
myPrepStmt.setDouble(1, drawingItem.getAnchor().getX());
myPrepStmt.setDouble(2, drawingItem.getAnchor().getY());
myPrepStmt.setDouble(3, drawingItem.getWidth());
myPrepStmt.setDouble(4, drawingItem.getHeight());
myPrepStmt.setDouble(5, ((Oval)drawingItem).getWeight());
myPrepStmt.setString(6, drawingItem.getColor().toString());
rowsAffected = myPrepStmt.executeUpdate();
closeConnection();

2 个答案:

答案 0 :(得分:4)

如建议的那样,使用参数化查询来防止SQL注入。至于手头的问题,你必须对每个字符串值使用单引号。

例如:

"('" + drawingItem.getAnchor().getX() +
"', '" + 

答案 1 :(得分:1)

正确的方法是:

String query = "INSERT INTO [oval] " +
               "(anchorX, anchorY, width, height, weight, color) VALUES " +
               "(?, ?, ?, ?, ?, ?)";

initConnection();
int i = 1;
Statement myStmt = con.prepareStatement(query);
myStmt.setInt(i++, drawingItem.getAnchor().getX());
myStmt.setInt(i++, drawingItem.getAnchor().getY());
myStmt.setString(i++, drawingItem.getWidth());
myStmt.setString(i++, drawingItem.getHeight());
myStmt.setFloat(i++, ((Oval) drawingItem).getWeight());
myStmt.setString(i++, drawingItem.getColor().toString());
rowsAffected = myStmt.executeUpdate();