優化上期代碼
針對查詢語句示例:
/**
* 優化
*/
@Test
public void selectDBpro() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "950404");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user ");
while (resultSet.next()){
int id = resultSet.getInt("id");
int age = resultSet.getInt("age");
String name = resultSet.getString("name");
System.out.println("id:" + id + "," + "age:" + age + "," + "name:" + name + "");
}
//不用的東西需要關閉
resultSet.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
//一旦不用,必須關閉連接的資源
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}