JDBC--Druid数据库连接池以及Template基本用法

数据库连接池
 1. 概念:其实就是一个容器(集合),存放数据库连接的容器。
当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。

 2. 好处:
        1. 节约资源
        2. 用户访问高效

Druid:数据库连接池实现技术,由阿里巴巴提供
         使用步骤:
            1. 导入jar包 druid-1.0.9.jar
            2. 定义配置文件:
                * 是properties形式的
                * 可以叫任意名称,可以放在任意目录下
            3. 加载配置文件。Properties
            4. 获取数据库连接池对象:通过工厂来来获取  DruidDataSourceFactory
            5. 获取连接:getConnection

配置文件:

driverClassName=com.mysql.jdbc.Driver  //驱动加载
url=jdbc:mysql://127.0.0.1:3306/DB1    //注册驱动
username=root                          //连接数据库的用户名
password=root                          //连接数据库的密码
initialSize=5                          //初始化时池中建立的物理连接个数
maxActive=10                           //最大的可活跃的连接池数量
maxWait=3000                           //获取连接时最大等待时间,单位毫秒,超过连接就会失效。

使用了druid连接池的工具类

public class JDBCUtils {
    private static DataSource ds;
    static {
        try {
            //加载配置文件
            Properties pro=new Properties();
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("Druid.properties");
            pro.load(is);
            //通过工厂获取连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //获取数据库连接对象
    public static DataSource getDataSource(){
        return ds;
    }
    //重载close方法
    public static void close(Statement stmt,Connection conn){
        close(null,stmt,conn);
    }
    //释放资源
    public static void close(ResultSet rs , Statement stmt, Connection conn){
        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();
            }
        }
    }

}

使用Druid得到连接Connection就可以执行相关JDBC操作了。

当然还有更方便的方法——JdbcTemplate

Spring JDBC
    * Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
    * 步骤:
        1. 导入jar包
        2. 创建JdbcTemplate对象。依赖于数据源DataSource
            * JdbcTemplate template = new JdbcTemplate(ds);

        3. 调用JdbcTemplate的方法来完成CRUD的操作
            * update():执行DML语句。增、删、改语句
            * queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
                * 注意:这个方法查询的结果集长度只能是1
            * queryForList():查询结果将结果集封装为list集合
                * 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
            * query():查询结果,将结果封装为JavaBean对象
                * query的参数:RowMapper
                    * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
                    * new BeanPropertyRowMapper<类型>(类型.class)
            * queryForObject:查询结果,将结果封装为对象
                * 一般用于聚合函数的查询

增删改:用update

public class tempDemo {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils2.getDataSource());

    public void test(){
        //使用template完成增删改
        String add_sql="insert into user values(NULL,'马化腾','123')";
        String de_sql="delete from user where id = 5 ";
        String up_sql="UPDATE USER SET username='马云' WHERE id =1";
        //update():执行DML语句。增、删、改语句
        template.update(add_sql);
        template.update(de_sql);
        template.update(up_sql);
    }
    public static void main(String[] args) {
         new tempDemo().test();//调用测试方法
    
    }
}

-->>>

 查询:用query系列

public class tempDemo {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils2.getDataSource());

    public void test(){
        //使用template完成增删改
        String add_sql="insert into user values(NULL,'马化腾','123')";
        String de_sql="delete from user where id = 5 ";
        String up_sql="UPDATE USER SET username='马云' WHERE id =1";
        //update():执行DML语句。增、删、改语句
        template.update(add_sql);
        template.update(de_sql);
        template.update(up_sql);
    }
    public void test2(){
        //使用template完成查询操作

        //定义sql
        String sql="select * from user where id = ?";
        String sql2="select id from user";
        String sql3="select * from user";
        //执行并打包成一个user类
        User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), 1);//最后的参数传的是?的值
        //执行打包成list集合
        List<Integer> list = template.queryForList(sql2, Integer.class);
        //执行并把user打包成集合
        List<User> query = template.query(sql3, new BeanPropertyRowMapper<User>(User.class));
        System.out.println("执行并打包成一个user类"+user);
        System.out.println("执行打包成list集合"+list);
        System.out.println("执行并把user打包成集合"+query);
    }
    public static void main(String[] args) {
//        new tempDemo().test();//调用测试方法
        new tempDemo().test2();
    }
}

 输出结果:

 信息: {dataSource-1} inited
执行并打包成一个user类User{id=1, username='马云', password='123'}
执行打包成list集合[1, 2, 7]
执行并把user打包成集合[User{id=1, username='马云', password='123'}, User{id=2, username='lisi', password='123'}, User{id=7, username='马化腾', password='123'}]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值