superche
superche

Reputation: 773

JDBC batch query for high performance

I want to do batch query DB for high performance, example sql to query based on different customer_id:

select order_id, 
       cost 
from customer c 
  join order o using(id) 
where c.id = ... 
order by

I'm not sure how to do it using JDBC statement. I know I can use stored procedure for this purpose, but it's much better if I can just write sql in Java app instead of SP.
I'm using DBCP for my Java client and MySQL DB.

Upvotes: 9

Views: 28510

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78639

The JDBC Specification 4.0 describes a mechanism for batch updates. As such, the batch features in JDBC can be used for insert or update purposes. This is described in chapter 14 of the specification.

AFAIK there is not a mechanism for select batches, probably because there is no apparent need for that since, as others have recommended, you can simply retrieve all the rows that you want at once by properly constructing your query.

int[] ids = { 1, 2, 3, 4 };
StringBuilder sql = new StringBuilder();
sql.append("select jedi_name from jedi where id in(");
for (int i = 0; i < ids.length; i++) {
    sql.append("?");
    if(i+1 < ids.length){
        sql.append(",");
    }
}
sql.append(")");
System.out.println(sql.toString());

try (Connection con = DriverManager.getConnection(...)) {

    PreparedStatement stm = con.prepareStatement(sql.toString());
    for(int i=0; i < ids.length; i++){
        stm.setInt(i+1, ids[i]);
    }

    ResultSet rs = stm.executeQuery();
    while (rs.next()) {
        System.out.println(rs.getString("jedi_name"));
    }

} catch (SQLException e) {
    e.printStackTrace();
}

Output

select jedi_name from jedi where id in(?,?,?,?)
Luke, Obiwan, Yoda, Mace Windu

Is there any reason why you would consider that you need a thing like a batch-select statement?

Upvotes: 10

aviad
aviad

Reputation: 8278

It is really does not matter what is your SQL statement (you can use as many nested joins as your DB can handle). Below is basic Java example (not DBCP). For DBCP example which is pretty similar you can check out their example.

Connection connect = DriverManager.getConnection(YOUR_CONNECTION_STRING);
// Statements allow to issue SQL queries to the database
Statement statement = connect.createStatement();

ResultSet resultSet = statement.executeQuery("select order_id, cost 
                                                from customer c 
                                                join order o using(id) 
                                                where c.id = ... 
                                            order by");

Upvotes: 0

Related Questions