规范化代码
所谓规范化代码就是无论是否出现异常, 都要关闭 ResultSet, Statement 以及 Connection,如果你还记得IO流的规范化代码,那么下面的代码你就明白什么意思了。
示例:
public void query() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null; // 在try外给出引用的定义
try{
con = getConnection(); // 在try内为对象实例化
stmt = con.createStatement();
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
while(rs.next()){
String username = rs.getString(1); // 获取第一列的值, 参数为列编号或列名
String password = rs.getString(2); // 获取第二列的值
System.out.println(username+","+password);
}
} catch(Exception e){
throw new RuntimeException(e);
} finally{
try{
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close(); // 在finally中进行关闭
} catch(SQLException e){
throw new RuntimeException(e);
}
}
测试类:
@Test
public void fun3() throws Exception{
Connection con = null; // 定义引用
Statement stmt = null;
ResultSet rs = null;
try {
/*
* 一、得到连接
*/
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "1234";
Class.forName(driverClassName);
con = DriverManager.getConnection(url,username,password); // 实例化
/*
* 二、创建Statment
*/
stmt = con.createStatement();
String sql = "SELECT * FROM emp";
rs = stmt.executeQuery(sql);
/*
* 三、循环遍历rs,打印其中数据
* getString()和getObject()是通用的
*/
while(rs.next()) {
System.out.println(rs.getObject(1) + "," + rs.getString("ename") + "," + rs.getDouble("sal"));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 关闭
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}
}