2

I was wondering if using PreparedStatement.setString() was a good idea (possible, sensible?) to dynamically build a query.

For example :

sql code:

SELECT * FROM table1 WHERE table1.category = ? ?

java code:

ps.setString(1,"category1");
ps.setString(2,"AND table1.category = 'category2'");

Also, would it be possible to do something like:

ps.setString(1,"category1");
ps.setString(2," AND table1.category = ?");
ps.setString(3,"category2");

Best regards

John Woo
  • 258,903
  • 69
  • 498
  • 492
BenoitParis
  • 3,166
  • 4
  • 29
  • 56

2 Answers2

9

Unfortunately, NO.

PreparedStatements are strictly for values only. Table Names and Column Names (as well as conditions in your example) are not allowed. So the best way to do is to concatenate it with the string.

String others = " AND table1.category = ?";
String query = "SELECT * FROM table1 WHERE table1.category = ? " + others;

java code:

ps.setString(1,"category1");
ps.setString(2,"category2");
John Woo
  • 258,903
  • 69
  • 498
  • 492
3

Whatever you put inside setString will go within single quotes ' ' and will not be interpreted as a query.

shazin
  • 21,379
  • 3
  • 54
  • 71