0

I would like to enter a group of numbers into a prepared statement all at once. Here is what I am trying

String parameters = "2,6,9";
preparedStatement = connection.prepareStatement("SELECT * FROM user WHERE id IN (?)");
preparedStatement.setString(1, parameters);

However this only give me back the first person (person 2). This is b/c I am sending a string within the IN parameters. When you print out preparedStatement.toString() to the console the result that's being sent to the db is

SELECT * FROM user WHERE id IN ('2,6,9')

So my problem is the surrounding ticks, and I need to somehow get them out. Any ideas?

Ps: I know I can split the string by commas and go down that path since I've already implemented it. However, I'd like to avoid this if possible. Looking for a better way.

gmustudent
  • 2,229
  • 6
  • 31
  • 43

1 Answers1

1

Try setting all the values:

PreparedStatement stmt = conn.prepareStatement(
    "select id, name from users where id in (?, ?, ?)");
stmt.setInt(1);
stmt.setInt(2);
stmt.setInt(3);

Note: This is from example on javaranch page given in this question.

Community
  • 1
  • 1
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188