繁体   English   中英

我可以使用相同的JDBC连接,语句和结果集在JDBC中执行两个查询

[英]can i use same JDBC connection, statement and resultset to execute two queries in JDBC

我正在验证用户

public static boolean login(DataManager dataManager, String userName, String password) {    
    boolean authenticated = false;      
    Connection connection = dataManager.getConnection();        
    if (connection != null) {           
         try {                           
             Statement s = connection.createStatement();
             String sql = "query";                 
             try {                   
                 ResultSet rs = s.executeQuery(sql);                                     
                 try {                      
                     while (rs.next()) {                             
                        String group_code = rs.getString(1);
                        String orgaunit = rs.getString(2);

                        authenticated = true;                            
                     } //end of while()                      
                 } finally {                     
                     rs.close();                     
                 }                   
             } finally {
                 s.close();                  
             }

         } catch(SQLException e) {               
             //System.out.println("Could not login from dataabse:" + e.getMessage());                
         } finally {             
             dataManager.putConnection(connection);                          
         }                  
    } //end of if (connection != null)      
    return authenticated;       
} //end of login()

我正在关闭dataManager.putConnection(connection) 我想问一旦用户登录然后我必须更新用户的状态并维护日志历史记录。 我可以使用这样的东西吗?

try {
    Statement s = connection.createStatement();
    String sql = "query";                 
    try {                    
        ResultSet rs = s.executeQuery(sql);                                  
        try {
            while (rs.next()) {                          
                String group_code = rs.getString(1);                                                
                authenticated = true;                            
            } //end of while()  

            if (autherntcated == true) {
                sql = "query2(update status)"; 
                rs = s.executeQuery(sql);

                while (rs.next()) {
                    //dos tuff
                }

                sql = "anotherQuery";
                rs = s.executeQuery(sql);
                while (rs.next()) {
                    //do stuff
                }

            }

        } finally {                      
            rs.close();                      
        }                    
    } finally {
        s.close();                   
    }                
} catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
} finally {              
    dataManager.putConnection(connection);                           
}

意味着使用相同的连接,相同的语句和相同的结果集执行其他查询或是错误的方法?

谢谢。

编辑------------------------------------------------- -------------

if (connection != null) {
    try {
        String sql = "query";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            ResultSet rs = prepStatement.executeQuery(sql);                 
            try {
                while (rs.next()) {
                    String group_code = rs.getString(1);
                    authenticated = true;
                } //end of while()
            } finally {                      
                rs.close();                      
            }
        } finally {
            prepStatement.close();                   
        }

        /// Addition   
        if (authenticated == true) {
            updateUser(connection, userName);
        }
    } catch(SQLException e) {
        //System.out.println("Could not login from dataabse:" + e.getMessage());
    } finally {
        dataManager.putConnection(connection);
    }
} //end of if (connection != null)

更新方法:

private static void updateUser(Connection connection, String userName) {

    try {
        String sql = "UPDATE users SET status_code = 'A' WHERE login_id = '" + userName + "'";    
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            int numberOfRowsUpdated = prepStatement.executeUpdate(sql);                 
        } finally {
            prepStatement.close();                   
        }

        maintainHistory(connection);

    } catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
    }

} //end of updateUser()

maintainHistory:

private static void maintainHistory(Connection connection) {

    try {
        String sql = "INSERT INTO auditlog_user_logins(user_code,logintime,prstid) VALUES ();";
        PreparedStatement prepStatement = connection.prepareStatement(sql);          
        try {            
          int numberOfRowsUpdated = prepStatement.executeUpdate(sql);                   

       } finally {

        prepStatement.close();                   

       }

     } catch(SQLException e) {

         //System.out.println("Could not login from dataabse:" + e.getMessage());

     }

} //end of maintainHistory()

我可以使用相同的JDBC连接语句

是。 您可以在关闭之前重复使用它们。

和结果集

不,这个问题没有意义。 结果集是执行查询或更新的结果。 毫无疑问可以重复使用它。 我想你需要在执行下一个查询或更新之前关闭前面的结果集。

我建议重用连接,因为每次尝试查询数据库时都建立连接可能是一个性能开销。

至于陈述,我建议切换到PreparedStatement。 它们不仅是缓存的,而且是保护自己免受SQL注入的一种好方法。 因此,事先建立您的查询,执行它们,并在完成后最终关闭它们。 重用PreparedStatement意味着您要将参数值替换为相同的PreparedStatement并执行相同的PreparedStatement。

例如,如果你有一个PreparedStatement,如:

PreparedStatement preparedStatement = connection.prepareStatement("SELECT [col_names] from [table_name] where [col_1_value] = ? and [col_2_value] = ?")

在这种情况下,只需将新值替换为参数,就可以多次重复使用相同的PreparedStatement 通常,对于您的情况,您将有多个PreparedStatements。 由于这些语句是缓存的,因此当您执行相同的语句时,它们不会对性能产生重大影响。

这是一个很好的教程,可以在您需要的时候向您介绍PreparedStatement: “使用准备好的语句”

结果集 - 我不知道你怎么能重用它。 当你完成它们时关闭它。 根据Javadoc

当生成它的Statement对象关闭,重新执行或用于从多个结果序列中检索下一个结果时,ResultSet对象将自动关闭。

但是,请确保在使用完毕后关闭连接。 可重用性是一件好事,但资源管理不善

用相同的问题回答了不同的测试用例。

我可以使用相同的JDBC连接,Statement和ResultSet在JDBC中执行两个查询

我们不能并行或并发地重用Connection,Statement和ResultSet,如下所示:

Connection con = databaseConnector.getConnection();
PreparedStatement stmt1=con.prepareStatement("select * from emp");  
ResultSet rs1=stmt.executeQuery();  
while(rs1.next()){  // get SQLException in second iteration
System.out.println(rs1.getInt(1)+" "+rs1.getString(2));  
    //As soon as you execute the following query, the previous Statement and ResultSet are implicitly closed.
    // to resolve we the problem, we should not use the above used Connection. We have to use new Connection.
    PreparedStatement stmt2=con.prepareStatement("select * from address");  
    ResultSet rs2=stmt2.executeQuery();  
    System.out.println(rs2.getString(1)+" "+rs2.getString(2));  

}  
  • 关闭一个Connection关闭一个Statement ,当Statement关闭时也会隐式关闭ResultSet
  • 关闭Statement关闭ResultSet但不会关闭Connection。
  • 关闭ReultSet只会自行关闭,而不是Statement
  • 默认情况下,每个Statement只能同时打开一个ResultSet

最佳实践:

  • 连接不是线程安全的,因此跨请求共享它们不是一个好主意。
  • 打开数据库连接是很昂贵的,应该使用ConnectionPool来共享连接。
  • 完成ResultSet使用后立即关闭ResultSet

您可以使用UpdatableResultSet

暂无
暂无

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

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