JDBC释放资源

 JDBCTest:

package com.test.example;

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

import com.mysql.jdbc.Driver;
import com.test.util.JDBCUtil;

public class JDBCTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			//1. 注册驱动 
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			//2. 建立连接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。
			 connection = DriverManager.getConnection("jdbc:mysql://localhost/jdbc", "root", "root");
			//3. 创建statement , 跟数据库打交道,一定需要这个对象
			 statement = connection.createStatement();
			//4. 执行查询 , 得到结果集
			String sql = "select * from stu";
            resultSet = statement.executeQuery(sql);
			//5. 遍历查询每一条记录
			while(resultSet.next()){
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				
				System.out.println("id="+id+",name="+name+",age="+age);
			}
//			resultSet.close();
//			Statement.close();
//			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JDBCUtil.close(connection, resultSet, statement);
		}

	}

}

JDBCUtil:
 

package com.test.util;

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

public class JDBCUtil {
	
	public static void close(Connection connection,ResultSet resultSet,Statement statement){
		closeRS(resultSet);
		closeSt(statement);
		closeConn(connection);
		
	}
	
	private static void closeRS(ResultSet resultSet){
		try {
			if(resultSet !=null){
				resultSet.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			resultSet = null;
		}
	}
	
	private static void closeSt(Statement statement){
		try {
			if(statement !=null){
				statement.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			statement = null;
		}
	}
	
	private static void closeConn(Connection connection){
		try {
			if(connection !=null){
				connection.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			connection = null;
		}
	}
	


}

运行结果:

数据库表: 

猜你喜欢

转载自blog.csdn.net/mqingo/article/details/84503366
今日推荐