使用配置文件与工具类创建mysql8.0连接

步骤:1. 准备配置文件 db.properties 

        2. 准备工具类代码.

1.db.prpoperties中的格式为:

jdbc.driver=com.mysql.cj.jdbc.Driver                             ( 适用于8.0版本的驱动)
jdbc.url=jdbc:mysql://localhost:3306/javaweb0312?allowPublicKeyRetrieval=true&serverTimezone=UTC&useSSL=false     ( 8.0版本需要加上)
jdbc.username=root 
jdbc.password=123

 

2.工具类中使用ThreadLocal 保证每个线程中只有一个连接.

首先读取配置文件.读取配置文件的过程是创建Properties 对象. 之后用获得的实例对象来加载 InputStream对象.

样例代码如下:

    private static String driver = null;
    private static String url = null;
    private static String password = null;
    private static String username = null;
    //获取Properties 实例对象
    private static Properties pro = new Properties();
    
    private static ThreadLocal<Connection> tl = new ThreadLocal();

  //在静态代码块中进行配置的读取.
static{ InputStream ins = ConnectionUtils.class.getClassLoader().getResourceAsStream("db.properties"); try { pro.load(ins); driver = pro.getProperty("jdbc.driver"); url = pro.getProperty("jdbc.url"); username = pro.getProperty("jdbc.username"); password = pro.getProperty("jdbc.password"); Class.forName(driver); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }

//获取连接的代码.首先从ThreadLocal中查看是否存在连接,不存在再建立连接,并且与ThreadLocal绑定.
public
static Connection getConnection() throws Exception{ Connection conn = tl.get(); if(conn == null){ conn = DriverManager.getConnection(url,username,password); tl.set(conn); } return conn; } //断开连接的代码,判断在ThreadLcoal中是否存在连接,如果存在,则关闭,之后将ThreadLocal中的连接置为null; public static void closeConnection() throws SQLException{ Connection conn = tl.get(); if(conn != null ){ conn.close(); } tl.set(null); }

 

posted @ 2020-03-13 15:19  男孩刘  阅读(393)  评论(0)    收藏  举报