1. 程式人生 > >JDBC學習筆記 -- day03 正確釋放資源的方法

JDBC學習筆記 -- day03 正確釋放資源的方法

1.正確釋放資源,需要加入異常處理機制

示例程式碼如下:

package com.jdcb.test;

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

import org.junit.Test;

import com.jdcb.entity.User;

public class JdbcTest {

	@Test
	public void selectTest() throws Exception {
		// 獲取連線
		Connection connection = null;
		// 獲取statement
		Statement statement = null;
		// 執行sql
		ResultSet resultSet = null;
		try {
			// 註冊驅動
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbc_demo", "root", "123");
			statement = connection.createStatement();
			resultSet = statement.executeQuery("SELECT * FROM users");
			// 處理結果集
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt(1));
				user.setName(resultSet.getString("name"));
				user.setPassword(resultSet.getString(3));
				user.setEmail(resultSet.getString("email"));
				user.setBirthday(resultSet.getDate("birthday"));
				System.out.println(user);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 釋放資源
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				resultSet = null; // 通知GC回收垃圾
			}
			if (statement != null) {
				try {
					statement.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				statement = null; // 通知GC回收垃圾
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				connection = null; // 通知GC回收垃圾
			}
		}

	}
}