• Druid连接池 dbutils包


    Druid连接池

    package com.JDBC;
    
    import com.alibaba.druid.pool.DruidDataSourceFactory;
    
    import javax.sql.DataSource;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.util.Properties;
    
    
    //Druid获取连接
    public class DruidTest {
        private static DataSource dataSource;
        static{
            try {
                InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
                Properties properties = new Properties();
                properties.load(inputStream);
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public static Connection getConnection() throws Exception {
            Connection connection = dataSource.getConnection();
            return connection;
        }
    }

    /* druid.properties
    url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf-8&useSSL=true
    username=root
    password=123456
    driverClassName=com.mysql.cj.jdbc.Driver
    */
    
    

    dbutils:(数据库操作工具类)

    package com;
    
    import com.JDBC.DruidTest;
    import com.JDBC.JDBCUtils;
    import org.apache.commons.dbutils.QueryRunner;
    import org.junit.Test;
    
    import java.sql.Connection;
    
    public class QueryRunnerTest {
        @Test
        public  void insertTest(){
            Connection connection = null;
            try {
                QueryRunner queryRunner = new QueryRunner();
                connection = DruidTest.getConnection();
                String sql = "insert into pet(name,age) values(?,?);";
                queryRunner.update(connection, sql, "Jie",5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                JDBCUtils.closeConnection(connection, null);
            }
        }
      
    @Test
    public void queryTest() {
    List<Pet> query = null;
    Connection connection = null;
    try {
    QueryRunner queryRunner = new QueryRunner();
    connection = DruidTest.getConnection();
    String sql = "select * from pet where age<?";
    BeanListHandler<Pet> petBeanHandler = new BeanListHandler<>(Pet.class);
    query = queryRunner.query(connection, sql, petBeanHandler, 6);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    JDBCUtils.closeConnection(connection, null);
    }
    query.forEach(System.out::println);
    }
    }
  • 相关阅读:
    5. 详解创建Vue实例传入的options【暂时3个】
    编程的小知识点:
    4. Vue的 MVVM模式
    3. Vue做一个计数器 --新属性:methods、新的指令:@click
    8. Spring 注解开发(原始注解)
    2. 第一个Vue程序
    1.VUE 的安装
    【洛谷 3388】割点
    【洛谷 1063】能量项链
    三堆石子
  • 原文地址:https://www.cnblogs.com/faded828x/p/13198774.html
Copyright © 2020-2023  润新知