0

I'm new in Prepared Statements, not sure if what I'm trying to do is legal or not.

 String updatequery = "Update articles SET Title = ? WHERE id IN ?";

    try{
        prestatement = connect.prepareStatement(updatequery);

        prestatement.setString(1, "Test");
        prestatement.setString(2,"(4,5,6)");

I get the following error:

Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in        your SQL syntax; check the manual that corresponds to your MySQL server version for the     right syntax to use near ''(4,5,6)'' at line 1

It seems like the setString() method is adding quotes to the query, is there a way to avoid this or another method to use to accomplish what I'm trying to do ?

neilnm
  • 183
  • 1
  • 3
  • 8

1 Answers1

0

try this:

final Collection<Integer> ids = Arrays.asList(4, 5, 6);

final StringBuilder updatequery = new StringBuilder("Update articles SET Title = ? WHERE id IN (");

for (int i = 0; i < ids.size(); i++) {
    updatequery.append("?,");
}

updatequery.deleteCharAt(updatequery.length() - 1);
updatequery.append(")");

System.out.println(updatequery);

prestatement.setString(1, "Test");
int i = 2;
for (final Integer id : ids) {
    prestatement.setInt(i ++, id);
}
Vasco Mars
  • 86
  • 3
  • I did try this and it does work but it's not as flexible as what I was hoping for since you need to change both the Prepared Statement and add a new setInt if more entries are needed. – neilnm Mar 10 '14 at 15:00
  • Is it flexible enought now? :-) – Vasco Mars Mar 10 '14 at 15:23