• 标准 mysql 数据库 jdbc 的两种写法 懒汉式 和 饿汉式


    饿汉式写法如下:  建议使用

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DataBaseConnection {
        private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
        private static final String DBURL = "jdbc:mysql://localhost:3306/test";
        private static final String DBUSER = "root";
        private static final String PASSWORD = "admin";
        public Connection conn;
    
        //饿汉式数据库连接
        public Connection getConnection() {
            try {
                if (conn == null && conn.isClosed())
                    Class.forName(DBDRIVER);
                conn = DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return conn;
        }
        public void close(){
            if(conn != null){
                try {
                    this.conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    懒汉式

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DatabaseConnection {
        private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
        private static final String DBURL = "jdbc:mysql://localhost:3306/test";
        private static final String DBUSER = "root";
        private static final String PASSWORD = "admin";
        private Connection conn = null;
    
        // 如果要实例化本类对象,实际上就是为了取得数据库连接,那么就把连接过程交给构造方法
        public DatabaseConnection() {
            try {
                Class.forName(DBDRIVER);
                this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        public Connection getConnection() {
            return this.conn;
        }
    
        public void close() {
            if (this.conn != null) {
                try { // 关闭时几乎不会有问题
                    this.conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    react 高阶组件之小学版
    react diff 极简版
    react 16更新
    react 组件的生命周期 超简版
    JS继承(简单理解版)
    Vue Virtual Dom 和 Diff原理(面试必备) 极简版
    Vue数据双向绑定(面试必备) 极简版
    Vue生命周期的执行过程(面试必备) 极简版
    多个Portal for ArcGIS 间的协作实操
    Portal的安全代理(反向代理出口)配置架构
  • 原文地址:https://www.cnblogs.com/arkia123/p/2736499.html
Copyright © 2020-2023  润新知