JDBC PreparedStatement查询

3

我正在使用Oracle数据库进行JDBC开发。 我有以下方法:

// 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*/
    ...
}

您可以看到,我正在尝试重用准备好的语句。 现在,我的问题是每次更改参数时是否会创建一个准备好的语句?

我只有在方法1中所有处理结束后才关闭语句。 我担心如果每次更改参数时都会创建一个新语句(因为我没有关闭所有语句),可能会出现未关闭的语句。 我应该担心吗?

谢谢,
Sash


这段代码是否能编译通过 fetchRecords(userStatement,); startRow=startRow+50; endRow=endRow+50; ? - Scary Wombat
1
@ScaryWombat 当参数名只是statement时,在fetchRecords内部使用userStatement - BackSlash
1
你有一个 PreparedStatement,你正在使用不同的参数多次使用它。这没有问题,并且不会生成额外的语句。同时,你也可以查看这个主题,可能会对你有所帮助:https://dev59.com/OnE95IYBdhLWcg3wE52C - Arnaud
1个回答

3

java.sql.PreparedStatement被设计为可重用的。

当您设置新参数时,将覆盖以前的参数,但不会创建新语句。

您还可以决定自己清除所有参数,使用clearParameters()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接