继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

java 连接 mysql 数据库 02

Curtis_yang
关注TA
已关注
手记 63
粉丝 62
获赞 1091
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();
        }
    }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP

热门评论

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

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

查看全部评论