Java JDBC的基础知识(二)

时间:2021-09-16 03:27:34

在我的上一篇Java JDBC的基础知识(一)中,最后演示的代码在关闭资源的时候,仅仅用了try/catch语句,这里是有很大的隐患的。在程序创建连接之后,如果不进行关闭,会消耗更多的资源。创建连接之后的代码挂掉了,后面的try/catch很难保证代码被执行。所以,这篇Java JDBC的基础知识(二)主要记录标准的异常处理。

一、要处理的代码如下

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test2 {
public static final String DRIVER = "com.mysql.jdbc.Driver";

public static void main(String[] args) throws SQLException {
try {
System.out.println(Class.forName(DRIVER));
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn
= DriverManager.getConnection(
"jdbc:mysql://localhost:3306/t_employee", "root", "root");
Statement stm
= conn.createStatement();
ResultSet rs
= stm.executeQuery("select*from t_employee");
while (rs.next()) {
System.out.print(rs.getInt(
"id") + "\t");
System.out.print(rs.getString(
"name") + "\t");
System.out.print(rs.getInt(
"age") + "\t");
System.out.println(rs.getInt(
"salary"));
}
try {
rs.close();
stm.close();
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

二、利用finally关闭资源

利用finally关闭资源的好处就是,不管将来程序挂不挂,都会关闭资源。另外,只有finally处理异常依然显得不够严谨,因为rs、stm、conn有可能为null,当他们为null时,再去执行.close()就会出现空指针异常。要引入if对rs、stm、conn进行判断。具体代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test2 {
public static final String DRIVER = "com.mysql.jdbc.Driver";

public static void main(String[] args) throws SQLException {

try {
System.out.println(Class.forName(DRIVER));
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}

Connection conn
= null;
Statement stm
= null;
ResultSet rs
= null;

try {
conn
= DriverManager.getConnection(
"jdbc:mysql://localhost:3306/t_employee", "root", "root");
stm
= conn.createStatement();
rs
= stm.executeQuery("select*from t_employee");
while (rs.next()) {
System.out.print(rs.getInt(
"id") + "\t");
System.out.print(rs.getString(
"name") + "\t");
System.out.print(rs.getInt(
"age") + "\t");
System.out.println(rs.getInt(
"salary"));
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
// finally里面的每個.close()都要分別try/catch,另外进行null判断
if (rs != null) {
try {
rs.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (stm != null) {
try {
stm.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

可见,上面的代码相当臃肿,如果每次写都要这样操作,整套代码就会很罗嗦,解决办法就是将他们封装起来。

之后会继续做相关学习介绍。