How to query database if we need to query with an array of id's in jsp?

After selecting some products a user clicked on proceed button. Now I need to display the selected data on next page. I was successful in getting the id's of selected data using the following code.

String[] array = request.getParameterValues("arrayid");

Now I need to query mysql database using "select * from table where id=?" I can use this query in a loop. But is there any other or a better way to do this?

Answers


String[] array = request.getParameterValues("arrayid");    
String sql = "SELECT * FROM TABLENAME WHERE id IN ?"; 
PreparedStatement ps = con.prepareStatement(sql);
ps.setArray(1,con.createArrayOf("CHAR", array));

Use IN keyword while selecting as select * from table where id IN(comma separated ids)


If your question is how to query for a set of IDs in a table, the other answers correctly refer you to SQL's IN keyword. However if you're asking specifically how to do it in Java, JDBC's PreparedStatement, which is the generally recommended way of executing queries in Java, does not make constructing these IN statements easy. I posted a suggested way to address this issue reasonably cleanly here: Can PreparedStatement.addBatch() be used for SELECT queries?


Need Your Help

'Max' Responsive Breakpoints in em

css responsive-design sass breakpoints em

I'm working on a responsive site using media queries in em, based around Bootstrap 3, using SASS.

jQuery - How to hide an element and its children?

javascript jquery html css

I have a div which I would like to hide along with all of its children. I thought that a simple selector.hide() would do the trick but it's still there.