- 1 #<!-- 连接设置 -->
- 2 driverClassName=com.mysql.cj.jdbc.Driver
- 3 url=jdbc:mysql://localhost:3306/test02
- 4 username=root
- 5 password=root
- 6
- 7 #<!-- 初始化连接 -->
- 8 initialSize=10
- 9
- 10 #<!-- 最大连接数量 -->
- 11 maxActive=50
- 12
- 13 #<!-- 最大空闲连接 -->
- 14 maxIdle=20
- 15
- 16 #<!-- 最小空闲连接 -->
- 17 minIdle=5
- 18
- 19 #<!-- 超时等待时间(单位毫秒) -->
- 20 maxWait=50000
- 21
- 22 #<!-- 编码方式 -->
- 23 connectionProperties=useUnicode=true;characterEncoding=utf8
- 24
- 25 ##<!-- 指定由连接池所创建的连接自动提交 -->
- 26 defaultAutoCommit=true
- 27
- 28 #<!-- 指定由连接池所创建的连接的事务级别 -->
- 29 defaultTransactionIsolation=REPEATABLE_READ
- 1 public class JdbcUtils_c3p0 {
- 2
- 3 private static DataSource dataSource;
- 4 static {
- 5 try {
- 6
- 7 //创建数据源 工厂模式 --》创建
- 8 dataSource = new ComboPooledDataSource();
- 9
- 10
- 11 } catch (Exception e) {
- 12 e.printStackTrace();
- 13 }
- 14 }
- 15
- 16 //获取连接
- 17 public static Connection getConnection() throws Exception{
- 18 return dataSource.getConnection();
- 19
- 20 }
- 21 //释放链接资源
- 22 public static void release(Connection connection, Statement statement, ResultSet resultSet){
- 23 try {
- 24 if (resultSet != null) {
- 25 resultSet.close();
- 26 }
- 27 if (statement != null) {
- 28 statement.close();
- 29 }
- 30 if (connection != null) {
- 31 connection.close();
- 32 }
- 33 }catch (Exception e){
- 34 e.printStackTrace();
- 35 }
- 36 }
- 37 }
- 1 Connection connection = null;
- 2 PreparedStatement ps = null;
- 3 ResultSet resultSet =null;
- 4 //1.获取数据库连接
- 5 try {
- 6 connection = JdbcUtils_c3p0.getConnection();
- 7 String sql = "insert into student (name,sex,birthday,tall) values (?,?,?,?)";
- 8 ps = connection.prepareStatement(sql); //预编译sql 先写sql,然后不执行
- 9 //手动为参数赋值
- 10 ps.setString(1, "嗷嗷嗷");
- 11 ps.setString(2, "男");
- 12 ps.setString(3, "2002.1.8");
- 13 ps.setDouble(4, 1.75);
- 14 //执行
- 15 ps.executeUpdate();
- 16
- 17 } catch (Exception e) {
- 18 e.printStackTrace();
- 19 } finally {
- 20 JdbcUtils.release(connection, ps, resultSet);
- 21 }
- 22 }