1. 导入 jar 包 jar包下载地址:https://mvnrepository.com/
导入IDEA,位置:project\lib
2. 配置文件 位置:project\src\c3p0.properties
1 2 3 4 5 # MySQL c3p0 数据库配置 c3p0.driverClass=com.mysql.jdbc.Driver c3p0.jdbcUrl=jdbc:mysql://localhost:3306/数据库名 c3p0.user=root c3p0.password=123456
3. 连接池工具类 C3P0DbUtils.java
1 2 3 4 5 6 7 8 9 10 11 import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3P0DbUtils { private static ComboPooledDataSource dataSource; static { dataSource = new ComboPooledDataSource (); } public static ComboPooledDataSource getDataSource () { return dataSource; } }
4. 执行SQL语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public class UserDaoImpl implements UserDao { private QueryRunner queryRunner = new QueryRunner (C3P0dbUtils.getDataSource()); @Override public int update (String action, User user) throws SQLException { if (null == action) { return -1 ; } String sql = null ; Object[] args = null ; if ("insert" .equals(action)) { sql = "insert into userinfo(username, password) value(?,?)" ; args = new Object []{user.getUsername(), user.getPassword()}; } else if ("delete" .equals(action)) { sql = "delete from userinfo where id=?" ; args = new Object []{user.getId()}; } else if ("update" .equals(action)) { sql = "update userinfo set username=?,password=? where id=?" ; args = new Object []{user.getUsername(), user.getPassword(), user.getId()}; } else { return -1 ; } System.out.println("sql=" + sql); System.out.println("args=" + args); return queryRunner.update(Objects.requireNonNull(sql), args); } @Override public User select (Integer id) throws SQLException { return queryRunner.query( "select * from userinfo where id=?" , new BeanHandler <>(User.class), id ); } @Override public List<User> selectALL () throws SQLException { return queryRunner.query( "select * from userinfo" , new BeanListHandler <>(User.class) ); } }