JDBC(自建工具类)

今天主要分享一下JDBC的工具类,自己写的不是很完善。其中每个地方都有注释。工具类可以帮助我们更简单的调用其方法和扩展。

public class JdbcUTIL {

	private JdbcUTIL() {

	}//私有构造,不可继承

	private static JdbcUTIL ju = new JdbcUTIL();

	public static JdbcUTIL getinsatnce() {
		return ju;
	}//饿汉模式,统一的访问

	private static List<Connection> pool;//连接池
	private static final int MAX_SIZE = 10;//常量,设置为10,连接池最大容量
	static {
		pool = Collections.synchronizedList(new ArrayList<>());//变为线程安全的,通过sollections工具类

		try {
			Connection conn;
			Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
			for (int i = 0; i < 3; i++) {//类加载时自动创建三个连接
				conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名?serverTimezone=UTC", "用户名",
						"密码);
				pool.add(conn);
			}
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public Connection getConnection() throws SQLException {//获取连接,如果池中剩余则取,无则新建
		Connection conn;
		if (pool != null && pool.size() > 0) {
			conn = pool.remove(pool.size() - 1);
		} else {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名?serverTimezone=UTC", "用户名",
					"密码);
		}
		return conn;
	}

	public void close(ResultSet rs, PreparedStatement ps, Connection conn) throws SQLException {//关闭连接资源
		try {
			if (rs != null)
				rs.close();
		} finally {
			try {
				if (ps != null)
					ps.close();
			} finally {
				reseletConn(conn);//前往释放方法
			}
		}
	}

	private void reseletConn(Connection conn) throws SQLException {//如果连接池满,则close()释放,如果不满则归入池中
		if (conn != null) {
			if (pool.size() < MAX_SIZE) {
				pool.add(conn);
			} else {
				conn.close();
			}
		}

	}

	public PreparedStatement createPreparedStatement(Connection conn, String sql, Object... params)
			throws SQLException {
		PreparedStatement ps = conn.prepareStatement(sql);
		if (params != null && params.length > 0) {//赋值问号占位符
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
		}

		return ps;

	}

	public ResultSet executeQuery(Connection conn, String sql, Object... params) throws SQLException {

		PreparedStatement ps = createPreparedStatement(conn, sql, params);

		return ps.executeQuery();//返回查询语句,结果集
	}

	public int executeUpdate(Connection conn, String sql, Object... params) throws SQLException {
		PreparedStatement ps = createPreparedStatement(conn, sql, params);
		return ps.executeUpdate();//返回增删改语句,被修改的行数

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值