手记

java 连接 mysql 数据库 02

package cn.mldn.dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {

    private static final String DBDRIVER = "com.mysql.jdbc.Driver";
    private static final String DBURL = "jdbc:mysql://localhost:3306/c";
    private static final String DBUSER = "root";
    private static final String PASSWORD = "";

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private static Connection rebuildConnection() throws Exception {
        Class.forName(DBDRIVER);
        return DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
    }

    public static Connection get() {
        Connection conn = threadLocal.get();
        try {
            if (conn == null) {
                conn = rebuildConnection();
                threadLocal.set(conn);
            }
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close() {
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            threadLocal.remove();
        }
    }
}
0人推荐
随时随地看视频
慕课网APP

热门评论

这个是学另外一视频网站发现的,觉得不错;

ThreadLocal 连接对象跟线程扯上关系,一般建议这么使用;

查看全部评论