package base;import java.sql.connection;import java.sql.drivermanager;import java.sql.resultset;import java.sql.sqlexception;import java.sql.statement;//tool classes that cannot be inherited public final class jdbcutilssingleton {//the privatization of member variables to prevent the other classes from affecting the common variables private string url = "JDBC:MYSQL://127.0.0.1:3306/JDBC";p rivate string username = "root";p rivate String password = "123456";p rivate static jdbcutilssingleton instance=null;//privatisation constructors to ensure that the Private jdbcutilssingleton () is not instantiated externally {}/** * take into account the concurrency needs of the yoke * @ Return */public static jdbcutilssingleton getinstance () {if (instance == null) { Synchronized (Jdbcutilssingleton.class) {if (instance == null) {instance = new Jdbcutilssingleton ();}}} Return instance;} Only one connection static{try {class.forname ("Com.mysql.jdbc.Driver") is created when the JVM is loaded;} catch (Classnotfoundexception e) {// todo auto-generated catch blocke.printstacktrace ();}} Get Connection public connection getconnection () throws SQLException{return Drivermanager.getconnection (Url, username, password);} Canonical Release resource method Public void free (Resultset rs,statement stmt,connection conn) {try{if (RS != null) Rs.close ();} catch (sqlexception e) {e.printstacktrace ();} Finally{try{if (Stmt != null) Stmt.close ();} catch (Sqlexception ex) {ex.printstacktrace ();} Finally{try{if (Conn != null) Conn.close ();} catch (Sqlexception em) {em.printstacktrace ();}}}}}
Summary of the main points of the single case model:
1. Privatization instance class variables and constructors ensure that the object is not instantiated externally, guaranteeing a unique singleton.
2. Take into account that the program concurrent processing needs to lock
3. Obtaining an instance through a unique entry static method: GetInstance ()
This article is from the "Love Coffee" blog, please be sure to keep this source http://4837471.blog.51cto.com/4827471/1589424
Get JDBC Connection singleton mode