jdbc连接第二种方法:

思想就是把获得driver、url、user、password的方法抽取到一个新的utils包,在包里创建一个
ConfigManager类,类里就是写一个双重锁的懒汉单例模式。
1、下面是步骤:
1、私有化构造方法
private ConfigManager (){
//把属性文件的内容读到pp集合就是在私有构造方法完成的
//new pp对象出来
Properties pp=new Properties();
//获得属性文件路径
String path=“属性文件名字”;
//通过反射获得属性文件的内容,参数是属性文件路径的字符串类型,并返回ips对象
InputStream ips=ConfigManager.class.getClassLoader.getResourceAsStream(path);
//利用pp的load方法读取内容
pp.load(ips);//参数是ips,所以在上面用反射获取属性文件的内容参数是路径,并得到ips的返回类型

		}
	**2、私有化静态的当前类对象**
		private static ConfigManager configManager=null;
	
	**3、提供一个对外的被获取对象的方法(双重锁方法,适用于分布式也非常的安全)**
		public static   ConfigManager getConfigManager(){
			if(configManager==null){
				//锁类目的不是安全,是为了反射能找到这个类,如果锁当前对象,反射找不到这类,就报异常。???
				synchronized(configManager.class){
					if(configManager==null){
						configManager=new ConfigManager;
					}
				}				
			}			
		}
	
	**4、再写一个获得属性文件键值对的值的方法**
	public String getValue(String key){
		//利用pp的getProperties方法
		return pp.getProperties(key);
	}
在BaseDao类里:
//前戏导入mysql-connector包、jdbc的属性文件
//在utils包创建一个双重锁的单例模式类,它可以根据键获得driver、url、user、	password的值

/*private Connection con;
//得到连接的方法
public Connection getCon(){
try {
Class.forName(ConfigManager.getConfigManager().getValue(“driver”));
con = DriverManager.getConnection(ConfigManager.getConfigManager().getValue(“url”),
ConfigManager.getConfigManager().getValue(“user”),
ConfigManager.getConfigManager().getValue(“password”));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}

//返回增删改结果集的方法(int)
public int methodUtils(String sql,Object[] obj){
int num = 0;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
num = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

//得到返回查询结果集的方法(ReturnResult)
public ResultSet getAll(String sql, Object[] obj){
ResultSet rs = null;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

//关闭所有连接对象的方法
public void doClose(ResultSet rs,PreparedStatement ps,Connection con) {
//从后关到前
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42334396/article/details/83305861