1
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();

I get:

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

What might be the problem?

8
  • can you share the full stacktrace please Commented Nov 21, 2019 at 14:48
  • which RDBS You are using? Commented Nov 21, 2019 at 14:50
  • It only prints "Error encountered: ERROR: syntax error at or near "INSERT INTO ws" Position: 1" Commented Nov 21, 2019 at 14:51
  • I am assuming its near like as the syntax for like is Like ' '.. It needs to have quotes Commented Nov 21, 2019 at 14:52
  • I use PostgreSQL Commented Nov 21, 2019 at 14:52

2 Answers 2

3

The subquery inside the VALUES clause looks suspicious. Try rephrasing as an 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();
Sign up to request clarification or add additional context in comments.

Comments

1

I would recommend insert . . . select:

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

This will not fix the problem with INSERT, but it will prevent the next problem of a subquery returning more than one row.

My best guess for that problem is that the library you are using only supports SELECT statements. That would be atypical; INSERT is usually allowed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.