jdbc-用线程池来进行数据库和jdbc的对接

用线程池来进行数据库和jdbc的对接

  • 这是一个连接数据库的工具类,通过它里面的方法可以直接实现和数据库的连接
/*
工具类:连接数据库的

 */
public class DBUtil {
    private static BasicDataSource bds;
    private static String url;
    private static String driver;
    private static String username;
    private static String password;
    private static int initial;
    private static int max;

    static {

        try { 
            //数据库用的线程池
            bds = new BasicDataSource();
            
            //创建properties对象用于储存该类文件的的数据
            Properties p = new Properties();
            
            //创建inputstream对象读取该类文件数据
            InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
            p.load(is);
            
            //将读取的赋值给定义好的变量
            url = p.getProperty("url");
            driver = p.getProperty("driver");
            username = p.getProperty("username");
            password = p.getProperty("password");
            initial = Integer.parseInt(p.getProperty("initial"));
            max = Integer.parseInt(p.getProperty("max"));

            //将变量的值赋值给数据库线程池
            bds.setUrl(url);
            bds.setUsername(username);
            bds.setDriverClassName(driver);
            bds.setPassword(password);
            bds.setInitialSize(initial);
            bds.setMaxActive(max);
        } catch (IOException e) {
            System.out.println("数据库获取信息出现异常");
            e.printStackTrace();
        }
    }


    public static Connection getConnection() {
        //创建connection对象
        Connection conn = null;
        try {
            
            //进行连接并把连接结果返回给connection对象
            conn = bds.getConnection();
            
        } catch (SQLException e) {
            System.out.println("数据库连接异常");
            e.printStackTrace();
        }


        return conn;
    }

    public static void closed(Connection conn) {
        try {
            conn.close();
        } catch (SQLException e) {
            System.out.println("数据库关闭异常");
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        Connection conn = getConnection();
        System.out.println(conn);
        System.out.println("数据库连接工具正常运行...............");
    }
}
  • properties文件内容

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/newdb3?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username=?
    password=?
    max=?
    initial=?
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值