一、优化之前的代码如下:
public class Test {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
statement = connection.createStatement();
String sql = "select * from user_info";
resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
String id = resultSet.getString("id");
String userName = resultSet.getString("user_name");
String password = resultSet.getString("password");
System.out.println(id+","+userName+","+password);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (resultSet!=null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (