Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set parameters dynamically to prepared Statement in JDBC

Tags:

java

jdbc

I have a common class for all DAO's where we will read queries and execute them as below. I will send parameters from DAO to this class.

Connection connection = Queries.getConnection();
String query = Queries.getQuery(queryName);//Queries i will get from xml
PreparedStatement preparedStatement =  connection.prepareStatement(query);

what is the best way to set parameters dynamically to prepared Statement in JDBC. I believe, we don't have named parameters concept in JDBC as we have in spring JDBC. We are only simple JDBC in our project.

like image 363
Java P Avatar asked Aug 02 '12 12:08

Java P


People also ask

Which Statement of JDBC should be used to set the values for the parameters for SQL dynamically?

Set parameters dynamically to prepared Statement in JDBC.

Which methods on the PreparedStatement can be used to bind the parameters?

The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three. A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods.

What is PreparedStatement and create it in JDBC?

The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.


1 Answers

write something like this:

public static int mapParams(PreparedStatement ps, Object... args) throws SQLException {
    int i = 1;
    for (Object arg : args) {         
         if (arg instanceof Date) {
        ps.setTimestamp(i++, new Timestamp(((Date) arg).getTime()));
    } else if (arg instanceof Integer) {
        ps.setInt(i++, (Integer) arg);
    } else if (arg instanceof Long) {
        ps.setLong(i++, (Long) arg);
    } else if (arg instanceof Double) {
        ps.setDouble(i++, (Double) arg);
    } else if (arg instanceof Float) {
        ps.setFloat(i++, (Float) arg);
    } else {
        ps.setString(i++, (String) arg);
    }
   }
  }
}

and in the queries just use '?' where you need to set the parameter.

I know that this is old school code, but just to give some minimalistic example...

like image 137
Andrey Borisov Avatar answered Sep 29 '22 23:09

Andrey Borisov