JDBCUtils 工具类

自己封装了一个JDBC类,已测试
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Statement;

public class JDBCUtils {
	static Properties properties = null;
/*	private final static String URL = "jdbc:mysql://localhost:3306/***";
	private final static String USER = "***";
	private final static String PASSWORD = "***";
	private final static String JDBCDRIVER = "com.mysql.jdbc.Driver";*/
	private JDBCUtils() {}
		
	//注册驱动
	static {
		try {
			properties = new Properties();
			try {
				properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
			} catch (IOException e) {
				System.out.println(JDBCUtils.class + "properties.load() error");
			}
			Class clazz = Class.forName(properties.getProperty("DBDRIVER"));
		}
		catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError();
		}
	}
	
	//获取连接
	public static Connection getConnection() throws SQLException {
		
		if(properties != null && !properties.getProperty("DBURL").isEmpty()
				&& !properties.getProperty("DBUSER").isEmpty()
				&& !properties.getProperty("DBPASSWORD").isEmpty()) {
			return DriverManager.getConnection(properties.getProperty("DBURL"), 
					properties.getProperty("DBUSER"), properties.getProperty("DBPASSWORD"));
		}
		
		return null;
		
		
	}
	
	//释放资源
	public static void close(Connection con, Statement ps, ResultSet rs) {
		closeConnection(con);
		closeStatement(ps);
		closeResultSet(rs);
	}
	
	public static void close(Connection con, Statement ps) {
		closeConnection(con);
		closeStatement(ps);
	}
	
	//释放连接 Connection
	public static void closeConnection(Connection con) {
		if(con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				System.err.println("释放连接 Connection 异常");
				e.printStackTrace();
			}
		}
		con = null;
	}
	
	//释放 Statement
	public static void closeStatement(Statement ps) {
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				System.err.println("释放 Statement 异常");
				e.printStackTrace();
			}
		}
		
		ps = null;
	}
	
	//释放 ResultSet
	public static void closeResultSet(ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				System.err.println("释放 ResultSet 异常");
				e.printStackTrace();
			}
		}
		
		rs = null;
	}
}

db.properties

*号的地方自己替换成自己的就可以了

DBDRIVER:com.mysql.jdbc.Driver
DBURL:jdbc:mysql://localhost:3306/***
DBUSER:***
DBPASSWORD:***

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值