简体   繁体   中英

JDBC with MySQL - SELECT … IN

Using PreparedStatement to build a query that looks like this...

SELECT * FROM table1 WHERE column1 IN ('foo', 'bar')

...without knowing the number of strings in the IN statement

Constructing a string like...

"'foo', 'bar'"

...and passing that in with ps.setString() results in:

"\'foo\', \'bar\'"

Which is probably a good thing, but it makes this approach to my problem useless.

Any ideas on how to pass in an unknown number of values into a JDBC PreparedStatement without dynamically creating the query string too (this query lives in a file for easy reuse and I'd like to keep it that way)?

I tend to use a method that will modify the query to modify the query accordingly. This is a basic example that omits error handling for simplicity:

public String addDynamicParameters(String query, List<Object> parameters) {
    StringBuilder queryBuilder = new StringBuilder(query);
    queryBuilder.append("?");
    for (int i = 1; i < parameters.size(); i++) {
        queryBuilder.append(", ?");
    }
    queryBuilder.append(") ");
    return queryBuilder.toString();
}

public void addParameters(PreparedStatement pstmt, List<Object> parameters) {
    int i = 1;
    for(Object param : parameters) {
        pstmt.setObject(i++, param);
    }
}

public void testDynamicParameters() {
    String query = "SELECT col3 FROM tableX WHERE col1 = ? AND col2 IN (";
    List<Object> parametersForIn = ...;
    query = addDynamicParameters(query, parametersForIn);
    List<Object> parameters = ...;
    PreparedStatement pstmt = ...; //using your Connection object...
    parameters.addAll(parametersForIn);
    addParameters(pstmt, parameters);
    //execute prepared statement...
    //clean resources...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM