java获得数据库-连接池(eclipse/ider/myeclipse)

首先要把自己的数据库工具打开(可以使用小皮里面的mysql视图工具或者自己去cmd直接输入命令)

导入自己的数据表

eclipse/ider/myeclipse(你用哪个工具都是一样)

文件一DbUtils.java

package com.qingruan.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

// 针对数据库的连接作用
public class DbUtils {
    
    //定义私有成员
    private static  DataSource ds;

    //1.静态代码块 加载配置文件,初始化连接池对象
    static{     // 特点:用于给类进行初始化,只加载一次,随着类的加载而加载
        try {
            Properties pro =new Properties();
            //加载属性文件
            pro.load(DbUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获得连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    
    //2.定义一个方法:获取连接对象
    public static Connection getConnection(){
        try {
            return  ds.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    //3.定义一个方法:用于释放资源    
    public static void close(ResultSet rs,PreparedStatement ps,Connection cn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(cn!=null){
            try {
                cn.close();  //  此时的关闭,是归还给连接池对象
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 获得连接池的方法
     * @return
     */
    public static  DataSource getDataSource(){
        return ds;
    }
    
}

文件二druid.properties

这里我的数据库密码root

我的数据库叫mysql

我的数据表叫store可以根据自己的改名字

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/store?characterEncoding=utf-8
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

以上不包括项目,只是数据库连接

Guess you like

Origin blog.csdn.net/weixin_52332409/article/details/127560902