注意
本工具类在使用前需要确保基础准备工作已完成
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>