I have the following snippet of a function that queries a PostgreSQL DB:
private void setQuery(String col1, String col2, String col3) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(
" SELECT t1.id,t1.uuid, t2.client_id,t1.start_time, t1.end_time, t1.state FROM t1, t2 WHERE t1.id=t2.id"
);
if (col1 != null && !col1.isEmpty()) {
stringBuilder.append(" AND t1.col1 = ?");
}
if (col2 != null && !col2.isEmpty()) {
stringBuilder.append(" AND t1.col2 = ?");
}
if (col3 != null && !col3.isEmpty()) {
stringBuilder.append(" AND t1.col3 = ?");
}
PreparedStatement pstmt = null;
try (Connection connection = connectionProvider.getConnection()) {
pstmt = connection.prepareStatement(stringBuilder.toString());
// how can I set the ? values in the stringBuilder, since they can be empty?
// pstmt.setString(1, col1);
// pstmt.setString(2, col2);
// pstmt.setString(3, col3);
} finally {
if (pstmt != null) pstmt.close();
}
}
Notice col1, col2, col3 can be empty or null, I need to add/remove those variables from the SQL query in case they are empty/null or not. Ideally, I would like to be allowed to append to the PreparedStatement, but I don't know how that's possible.
What would be the best way to achieve this? How can I properly set the values into the prepared statement?