try(){}写法会自动关闭连接

String sql = "select password from user where name = ?";                              
try(Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){ 
    ps.setString(1, userName);                                                        
    ResultSet rs = ps.executeQuery();                                                 
    if(rs.next())                                                                     
        return rs.getString("password");                                              
} catch (SQLException e) {                                                            
    e.printStackTrace();                                                              
}                                                                                     

 

相关文章: