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

Java 我可以使用相同的JDBC连接、语句和结果集在JDBC中执行两个查询吗,java,jdbc,Java,Jdbc,我正在对用户进行身份验证 public static boolean login(DataManager dataManager, String userName, String password) { boolean authenticated = false; Connection connection = dataManager.getConnection(); if (connection != null) {

我正在对用户进行身份验证

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()
我正在关闭
数据管理器中的连接。putConnection(连接)
。我想问一旦用户登录,然后我必须更新用户的状态和维护日志历史记录。我能用这样的吗

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()
维护历史记录:

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()

我建议重用连接,因为每次尝试查询数据库时建立连接可能会带来性能开销

至于报表,我建议切换到PreparedStatement。它们不仅是缓存的,而且是防止SQL注入的一种好方法。所以,先建立查询,然后执行它们,最后在完成后关闭它们。重用PreparedStatement意味着用参数值替换同一PreparedStatement并执行相同的语句

例如,如果您有一个准备好的语句,如:

PreparedStatement preparedStatement = connection.prepareStatement("SELECT [col_names] from [table_name] where [col_1_value] = ? and [col_2_value] = ?")
在这种情况下,只需用新值替换参数,就可以多次重用同一PreparedStatement。一般来说,对于您的案例,您会有多份准备好的陈述。因为这些语句是缓存的,所以当您执行相同的语句时,它们不会对性能造成太大影响

这里有一个很好的教程,可以向您介绍PreparedStatement,以防您需要它:

结果集-我不知道你怎么能重用它。当你用完它们时,把它关上。根据:

语句对象关闭时,ResultSet对象将自动关闭 生成它的文件将被关闭、重新执行或用于检索下一个文件 由多个结果序列生成的结果

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

我可以使用相同的JDBC连接吗

对。您可以在关闭之前重新使用它们

和结果集


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

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

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

我们不能并行或并发重用连接、语句和结果集,如下所示:

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));  

}  
  • 关闭
    连接
    会关闭
    语句
    ,而
    语句
    关闭也会隐式关闭
    结果集
  • 关闭
    语句
    会关闭
    结果集
    ,但不会关闭连接
  • 关闭
    ReultSet
    只关闭自身,而不是
    语句
  • 默认情况下,每个
    语句
    只能同时打开一个
    结果集
最佳实践:

  • 连接不是线程安全的,所以跨请求共享它们不是一个好主意
  • 打开DB连接是一项昂贵的任务,应该使用ConnectionPool来共享连接
  • 使用完
    ResultSet
    后,立即关闭
    ResultSet

您的意思是说我可以关闭语句和结果集。我的意思是,一旦我关闭了语句和结果集,然后以相同的方式使用update和另一个查询,然后关闭数据库连接
dataManager.putConnection(连接)。是吗?@Basit:更新了我的答案,包含了更多信息。理想情况下,您希望重用连接对象。ResultSet没有意义,就像我指定的那样,我建议从语句移动到PreparedStatement,就像我创建语句
Statement s=connection.createStatement()时一样然后我必须关闭它。我是否也需要以与处理报表相同的方式关闭准备好的报表?我首先使用连接创建语句,然后使用
s.executeQuery(query)
获取
ResultSet
,然后循环遍历结果集。我怎样才能用PreparedStatement替换它?@Basit:是的,您必须在处理完PreparedStatement后关闭它。您可以在“我编辑了我的代码”中阅读有关如何使用它的更多信息。你能检查一下我的方式是否正确吗?看起来还可以,但你没有重复使用任何
语句
PreparedStatement
,这显然不是你需要的。我不明白你的代码应该证明什么或在这里展示什么。