mysql单例模式

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”输出两次,说明连接两次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值