天天看点

JDBC连接MySQL数据库工具类

配置文件

在项目的 resources 资源文件夹中,添加一个 MySQLJDBC.properties文件,文件内容示例如下:

driver =com.mysql.jdbc.Driver
jdbcurl = jdbc:mysql://192.168.100.61:3306/orclstaff?autoReconnect=true&useUnicode=true&characterEncoding=utf8
userName = root
password = root
handleTable = COFCO_MEMBER
           

代码展示

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;

//连接mysql驱动的工具类
public class JDBCUtils {
    //Connection的线程池,保证连接资源不浪费
    private static ThreadLocal<Connection> connThreadLocal = new ThreadLocal<>();

    //私有构造
    private JDBCUtils() {}

    /**
     * 获取JDBC连接的Connection对象
     * @return
     */
    public static synchronized Connection getConnection() {
        Connection conn = null;
        //如果Connection线程池中存在已经申请的连接,则直接获取,否则重新初始化连接
        if (connThreadLocal.get() != null) {
            conn = connThreadLocal.get();
        } else {
            //读取JDBC连接的配置文件
            ResourceBundle bundle = ResourceBundle.getBundle("MySQLJDBC");
            String driverClass = bundle.getString("driver");
            String url = bundle.getString("jdbcurl");
            String user = bundle.getString("userName");
            String password = bundle.getString("password");

            //注册驱动
            try {
                Class.forName(driverClass);
                conn = DriverManager.getConnection(url, user, password);
                //将获取的Connection对象放入本类的Connection线程池中
                connThreadLocal.set(conn);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    /**
     * 关闭释放JDBC资源
     */
    public static void closeJDBCResource(PreparedStatement ps) {
        Connection conn = connThreadLocal.get();
        //如果连接对象不为空就释放资源
        if (conn != null) {
            try {
                conn.close();
                connThreadLocal.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}