mysql单例模式

2019-04-13 20:41发布

package dao; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties; /**
*
* @author Administrator
*
*/
public class daotest {
private static daotest dao = null;
static String dbUrl = “jdbc:mysql://192.168.2.13:3306/bazhuayu?useUnicode=true&characterEncoding=utf-8”;
static String dbUser = “yoya”;
static String dbPass = “yoya123456”; /* * 私有化构造方法 */ private daotest(){} /** * 懒汉式的单例 * @return */ public static synchronized daotest getDao(){ if(dao == null){ dao = new daotest(); System.out.println("111"); } return dao; } public static Connection getConn() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); System.out.println("222"); return DriverManager.getConnection(dbUrl , dbUser , dbPass); } /** * 关闭数据库连接 * @param rs * @param pstmt * @param conn */ public void closeConn(ResultSet rs,Statement pstmt,Connection conn){ try { if (rs!=null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (pstmt!=null) { pstmt.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (conn!=null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } }
package dao; import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement; public class test { public boolean distinct(){ boolean rs = true; daotest d = daotest.getDao(); String sql = "delete from information.info where id = '18365'"; try { Connection conn = d.getConn(); Statement st = conn.createStatement(); rs = st.execute(sql); } catch (Exception e) { e.printStackTrace(); } return rs; } public static void main(String[] args) { test t = new test(); System.out.println(t.distinct()); test tt = new test(); System.out.println(tt.distinct()); } } 最测试:“111”输出一次,说明单例模式成功。
“222”输出两次,说明连接两次。