书写jdbcUtil工具类使用C3P0数据库连接池

注意

本工具类在使用前需要确保基础准备工作已完成
1: mysql c3p0共 3个jar包(log4j也可以添加)
2: c3p0配置文件配置相应属性(如果导入了log4j那么也需要配置log4j配置文件)

public class jdbcUtil {
	final static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
	// 获取连接方法
    // 返回一个连接对象
	public static Connection getCon(){
		// 连接使用c3p0进行获取
		// 使用c3p0数据库连接池获取连接
		Connection connection = null;
		try {
			connection = comboPooledDataSource.getConnection();				
		} catch (SQLException e) {
			System.err.println("获取连接失败");
			return null;
		}
		return connection;
	}
	//DML方法,不支持事物
	public static boolean DML(String sql,Object...o){
		// 获取连接
		Connection con = getCon();
		// 创建预编译对象
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			for(int i=0;i<o.length;i++){
				ps.setObject((i+1), o[i]);
			}
			ps.executeUpdate();
		} catch (SQLException e) {
			System.out.println("查询执行失败:" + sql);
			return false;
		}
		return true;		
	}
	// DML方法 支持事物
	public static boolean DML(Connection con, String sql, Object... o){
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			for (int i = 0; i < o.length; i++) {
				ps.setObject((i + 1), o[i]);
			}
			ps.executeUpdate();
		} catch (SQLException e) {
			System.out.println("查询执行失败:" + sql);
			try {
				con.rollback();
			} catch (SQLException e1) {
				
				e1.printStackTrace();
			}
		}
		
		return true;		
	}
	//查询DQL语句方法
	public static <E> ArrayList<E> DQL(String sql, Class<E> c, Object... o){
		ArrayList<E> list = new ArrayList<>();
		try {//获取连接
		Connection con = getCon();
		//准备预编译对象		
		PreparedStatement ps = con.prepareStatement(sql);
		// 获取元数据 准备存储所有列名的数组
		for (int i = 0; i < o.length; i++) {
				ps.setObject((i + 1), o[i]);
			}
		ResultSetMetaData metaData = ps.getMetaData();
		// 创建指定长度用于存储列名的数组
		String[] names=new String [metaData.getColumnCount()];
		// 循环为names数组进行赋值
		for(int i=0;i<names.length;i++){
			names[i]=metaData.getColumnLabel(i+1);
		}
		// 执行sql返回结果集
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			// 使用反射创建对象
			E obj = c.newInstance();
			// 当前行所有列名 在names数组中存储
			// 循环names数组取出当前行对应数据
			for (String string : names) {
				Object value = rs.getObject(string);
				// 将值存入相应对象
				// 使用反射获取类中同名的属性对象
				Field field = c.getDeclaredField(string);
				// 私有属性使用前必须赋权
				field.setAccessible(true);
				// 调用属性对象的set方法为指定对象进行赋值
				field.set(obj, value);	
			}
			list.add(obj);			
		}
		
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return list;		
	}		
}

c3p0的配置文件

文件名必须为c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<!-- 这是默认配置信息 -->
	<default-config>
		<!-- 连接四大参数配置 -->
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/homework?characterEncoding=UTF-8</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">root</property>
		<!-- 池参数配置 -->
		<!-- 如果池中数据连接不够时一次增长多少个 -->
        <property name="acquireIncrement">5</property>
        <!-- 初始化数据库连接池时连接的数量 -->
        <property name="initialPoolSize">20</property>
        <!-- 数据库连接池中的最大的数据库连接数 -->
        <property name="maxPoolSize">25</property>
        <!-- 数据库连接池中的最小的数据库连接数 -->
        <property name="minPoolSize">5</property>

	</default-config>
</c3p0-config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JDBCUtil是一个用于管理JDBC连接的工具类。它可以帮助你轻松地创建、释放和管理数据库连接,同时也提供了一些方便的方法来执行SQL语句和获取结果集。 以下是一个JDBCUtil工具类的示例: ```java import java.sql.*; public class JDBCUtil { private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } public static void release(Connection conn, Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void execute(String sql) { Connection conn = null; Statement stmt = null; try { conn = getConnection(); stmt = conn.createStatement(); stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } finally { release(conn, stmt, null); } } public static ResultSet executeQuery(String sql) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } } ``` 这个工具类包含了以下几个方法: - `getConnection()`:获取数据库连接。 - `release(Connection conn, Statement stmt, ResultSet rs)`:释放数据库资源。 - `execute(String sql)`:执行SQL语句。 - `executeQuery(String sql)`:执行查询语句并返回结果集。 你可以通过以下方式来使用这个工具类: ```java public static void main(String[] args) { Connection conn = JDBCUtil.getConnection(); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM user"); while (rs.next()) { System.out.println(rs.getString("username")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.release(conn, stmt, rs); } } ``` 上面的代码中,我们首先使用`getConnection()`方法获取数据库连接,然后利用这个连接创建一个`Statement`对象并执行查询语句。最后,我们使用`release()`方法释放数据库资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值