How to create a dynamically prepared statement in Java?

I know that using prepared statements helps to avoid sql injections. My problem is that the prepared expression is usually very static. I have a problem when I create a sql query where clause at runtime, depending on user input. Depending on which input fields are populated, I have to add the statements of conforming to where-clause. How can this be implemented using prepared statements?

+2
source share
5 answers

I think you could dynamically create your prepared statements based on which columns they want to query, i.e. use a StringBuffer and a loop to create them based on the required columns.

For efficiency, you must keep them in some search in mind. Thus, you will receive a map or other collection of prepared statements, where the search key is the columns for which they are requested.

+3
source

where/and clause (s) , , , , , . , , , , .

//something similar to the following
public String buildQuery(int option){
  StringBuilder sb = new StringBuilder();
  sb.append("select fields from table");
  switch(option){
    case 1:
     //build query and append to sb
     sb.append("where clause for option1");
    case 2:
     //build query and append to sb
     sb.append("where clause for option2");
    default:
    // build query using default
    sb.append("default where clause");
  }

  return sb.toString();
}
// create the stored procedure
PreparedStatement ps = conn.prepareStatement(buildQuery(2));
ResultSet rs = ps.executeQuery();

, , , .

ps.setString(1,list.get(0));
ps.setString(2,list.get(1));
ResultSet rs = ps.executeQuery();

, , , , . , .

+3

sql-, , , ( , - , ).

- . , DB , , , , . , .

+2

Hibernate, Criteria Queries API - SQL-. JDBC StringBuffer, @Jhonatan.

0

Declare one method and pass userinput through this method. Then use setStringor setLongdepending on your input type within the prepared object.

-1
source

All Articles