JDBCUtils 连接工具: druid的

package cn.itcast.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

// 使用 druid连接池。
public class JDBCUtils {
     private  static DataSource  ds;

     static {
         try {
             // 加载配置文件“
             Properties pro=new Properties();
             // 使用classLoader 加载配置文件,获取字节输入流。
             InputStream is=JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
             pro.load(is);


             // 初始化连接对象:
             ds= DruidDataSourceFactory.createDataSource(pro);

         }catch (Exception e){
             e.printStackTrace();
         }
     }
    //获取连接池对象。
    public static DataSource getDataSource(){ return  ds;}


    //获取连接connection对象
    public  static Connection getConnection() throws SQLException {
         return ds.getConnection();
    }

}

 

 

 

使用的情况:

 private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<User> findAll() {
        //使用jdbc操作数据库。
        // 定义sql。
        String sql="select  *  from user";
        List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));


        return list;
    }

 

 

 

连接所需要使用的 连接配置文件:

# druid.properties文件的配置
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/?????characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true 
username=root
password=522636
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大超时时间
maxWait=3000

 

posted @ 2021-11-28 11:47  九块钱的代码  阅读(98)  评论(0)    收藏  举报