饿汉式写法如下: 建议使用
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(); } } } }