为什么会出现“ INSERT INTO”的语法错误?

时间:2019-11-21 14:46:26

标签: sql postgresql jdbc

String pName = getStrFromUser("Product name: ");
int price = getIntFromUser("Price: ", false);
String category = getStrFromUser("Category: ");
String description = getStrFromUser("Description: ");

PreparedStatement statement = connection.prepareStatement("INSERT INTO ws.products (name, price, cid, description) VALUES (?, ?, (SELECT ws.categories.cid FROM ws.categories WHERE ws.categories.name LIKE ?), ?)");

statement.setString(1, pName);
statement.setInt(2, price);
statement.setString(3, category);
statement.setString(4, description);
statement.executeUpdate();

我得到:

Error encountered: ERROR: syntax error at or near "INSERT INTO ws

可能是什么问题?

2 个答案:

答案 0 :(得分:3)

VALUES子句中的子查询看起来可疑。尝试改写为INSERT INTO ... SELECT

String sql = "INSERT INTO ws.products (name, price, cid, description) ";
sql += "SELECT ?, ?, cid, ? FROM ws.categories WHERE name LIKE ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, pName);
statement.setInt(2, price);
statement.setString(3, description);
statement.setString(4, category);
statement.executeUpdate();

答案 1 :(得分:1)

我会推荐insert . . . select

INSERT INTO ws.products (name, price, cid, description) 
    SELECT ?, ?, ws.categories.cid, ?
    FROM ws.categories
    WHERE ws.categories.name LIKE ?;

这不能解决INSERT的问题,但可以防止子查询返回多行的 next 问题。

我对该问题的最佳猜测是您使用的库仅支持SELECT语句。那将是非典型的。通常允许使用INSERT