JDBC数据库操作中如何保证最后关闭了所占用的资源——try用法的细节控制

JDBC数据库操作中如何保证最后关闭了所占用的资源——try用法的细节控制

在java对数据库的JDBC开发中,往往需要确认最后释放数据库的连接资源,避免连接池被占用。
传统的方法是:
连接数据库后,定义连接和语句,然后执行响应的sql语句,执行完毕后,用close()依次逆序关闭statement语句和连接。经典代码如下:

	Connection connection = null;
	Statement statement = null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			connection = DriverManager.getConnection(URL, UNAME, UPASS);
			statement = connection.createStatement();
			String sqlString = "insert into ...";//略
			if (statement.executeUpdate(sqlString) > 0) {
				System.out.println("插入成功");
			}
		}catch (SQLException e) {
....
		}
		finally {
			try {
				if (statement!=null) statement.close();
				if (connection!=null) connection.close();		
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}

在JDK8.0以后,只要把所需要关闭的资源在try{}中完成声明,在最后系统会自动依次关闭其中的资源。非常适合用于管理statement、resultRecords等数据库操作中产生的短时资源。
而对于connection,当需要连续操作数据库时,仍然建议放在try之外定义,并手动控制关闭。
代码如下:

		Connection connection = null;
		try {
			Statement statement = null;//statement放在try中,结束后会自动关闭
			Class.forName("com.mysql.cj.jdbc.Driver");
			connection = DriverManager.getConnection(URL, UNAME, UPASS);
			statement = connection.createStatement();
			String sqlString = "insert into ...";//略
			if (statement.executeUpdate(sqlString) > 0) {
				System.out.println("插入成功");
			}
			...//还可以完成更多的sql操作
		}catch (SQLException e) {
....
		}
		finally {
			try {
				if (connection!=null) connection.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}

Connection,也可以放入try{}中声明,将会在执行完毕后,全部由系统自动关闭。
例如:
代码如下:

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			Connection connection = DriverManager.getConnection(URL, UNAME, UPASS);
			Statement statement = connection.createStatement();//statement放在try中,结束后会自动关闭
			String sqlString = "insert into ...";//略
			if (statement.executeUpdate(sqlString) > 0) {
				System.out.println("插入成功");
			}
			...//还可以完成更多的sql操作
		}catch (SQLException e) {
....
		}
		finally {
			System.out.println("系统关闭全部资源");
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值