简体   繁体   中英

JDBC PreparedStatement Query

I'm working on JDBC with Oracle database. I have the below methods:

// Method1
public void method1(){
    Connection connection=ConnectionFactory.getRemoteConnection();
    selectSQL = "select * tablename where num>=? and num<=?";
    PreparedStatement userStatement=connection.prepareStatement(selectSQL);
    userStatement.setFetchSize(500);
    int i=0;
    int startRow=0;
    int endRow=50;
    do{
       // Reusing the statement
       fetchRecords(userStatement,startRow,endRow);
       startRow=startRow+50;
       endRow=endRow+50;
       i++;
       if(i==50) endOfRows=true;
    }while(!endOfRows);
    userStatement.close();
}

// Method2
public List<String> fetchRecords(PreparedStatement userStatement,int startRow,int endRow){
    userStatement.setInt(1, startRow);
    userStatement.setInt(2, endRow);
    resultSet = userStatement.executeQuery();
    /*Some logic*/
    ...
}

As you can see, I'm trying to reuse a prepared statement. Now, my question is while a prepared statement be created everytime I change parameters?

I'm closing the statement only after the end of all the processing in method1. I'm worried if a new statement is created everytime I change the parameters (since I'm not closing all of them), it may end up in un-closed statement. Should I be worried?

Thank you,
Sash

java.sql.PreparedStatement is designed to be reusable.

When you set new parameters, you will overwrite the previous ones but you will not create a new Statement.

You can also decide to clear all the parameters yourself using clearParameters()

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