java - JDBC with MySQL - SELECT ... IN -
using preparedstatement build query looks this...
select * table1 column1 in ('foo', 'bar')
...without knowing number of strings in in statement
constructing string like...
"'foo', 'bar'"
...and passing in ps.setstring() results in:
"\'foo\', \'bar\'"
which thing, makes approach problem useless.
any ideas on how pass in unknown number of values jdbc preparedstatement without dynamically creating query string (this query lives in file easy reuse , i'd keep way)?
i tend use method modify query modify query accordingly. basic example omits error handling simplicity:
public string adddynamicparameters(string query, list<object> parameters) { stringbuilder querybuilder = new stringbuilder(query); querybuilder.append("?"); (int = 1; < parameters.size(); i++) { querybuilder.append(", ?"); } querybuilder.append(") "); return querybuilder.tostring(); } public void addparameters(preparedstatement pstmt, list<object> parameters) { int = 1; for(object param : parameters) { pstmt.setobject(i++, param); } } public void testdynamicparameters() { string query = "select col3 tablex col1 = ? , col2 in ("; list<object> parametersforin = ...; query = adddynamicparameters(query, parametersforin); list<object> parameters = ...; preparedstatement pstmt = ...; //using connection object... parameters.addall(parametersforin); addparameters(pstmt, parameters); //execute prepared statement... //clean resources... }
Comments
Post a Comment