简体   繁体   English

JDBC PreparedStatement查询

[英]JDBC PreparedStatement Query

I'm working on JDBC with Oracle database. 我正在使用Oracle数据库进行JDBC。 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. 我只是在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. java.sql.PreparedStatement旨在可重用。

When you set new parameters, you will overwrite the previous ones but you will not create a new Statement. 设置新参数时,将覆盖之前的参数,但不会创建新的Statement。

You can also decide to clear all the parameters yourself using clearParameters() 您还可以决定使用clearParameters()自行清除所有参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM