JDBC连接获取的两种方式及其步骤

JDBC方式
1.准备好数据库连接信息
2.准备好数据库连接驱动
3.加载好数据库连接信息
4.加载好数据库连接驱动
5.设置好驱动来获取连接

public class JdbcUtil {
    private static String driver,url,user,password;
    private static InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
    private static Properties properties=new Properties();
    private static Connection conn;

    static {
        try {
            properties.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection() {
        try {
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(driver.trim()); // 加载driver以执行其静态初始代码块来实现向DriverManager注册driver
            conn = DriverManager.getConnection(url, user, password);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql?useTimezone=true&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
user=root
password=admin

连接池方式
1.准备好数据库连接信息和连接池配置信息
2.准备好数据库连接驱动和连接池支持类库
3.加载好数据库连接信息和连接池配置信息
4.配置好数据源用连接信息连接池配置信息
5.获取数据库连接用配置好的数据源

 

public class JdbcUtil {
    private static String driver,url,user,password;
    private static InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");//JdbcUtil也可以用BaseDao代替
    private static Properties properties=new Properties();
    private static DataSource dataSource;    
    private static Connection conn;

    static {
        try {
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection() {
        try {
            conn=dataSource.getConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}

 

druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql?useTimezone=true&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
username=root
password=admin
initialSize=5
maxActive=10

posted on 2022-02-20 11:06  金满仓  阅读(275)  评论(0)    收藏  举报

导航