JDBC代码规范化

时间:2021-10-30 07:23:12

JDBC规范化代码

所谓代码规范化就是无论是否出现异常,都要关闭ResultSet、Statement,以及Connection。

一个访问数据库的类Test1 的代码如下:

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test1 {


public static Connection getConnection() throws ClassNotFoundException,
SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
return DriverManager.getConnection(url, "root", "123");
}

public static void main(String[] args) {


Connection con = null;       //在try块外声明变量并初始化
PreparedStatement ps = null;
ResultSet rs = null;
try {                                            //在try块内实例化对象,并赋值给上述变量
con = getConnection();
String sql = "select * from user";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String userId = rs.getString(1);
String userName = rs.getString(2);
System.out.println(userId + ", " + userName);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {                                        //在finally中进行关闭

try {

if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (con != null)
con.close();

} catch (SQLException e) {

                              throw new RuntimeException(e);

}
}
}
}