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
可能是什么问题?
答案 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
。