package com.csdn.dao;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 单例模式
*
* @author Administrator
*
*/
public class ConfigManager {
// 1.创建私有属性
private static ConfigManager configManager;
private static Properties properties;
// 2.创建私有构造器
private ConfigManager() {
// 3.获取配置文件
properties = new Properties();
InputStream is = ConfigManager.class.getClassLoader()
.getResourceAsStream("database.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
// 4.公有的方法(双重锁)
public static synchronized ConfigManager getConfigManager() {
if (configManager == null) {
synchronized (ConfigManager.class) {
configManager = new ConfigManager();
}
}
return configManager;
}
//5.拿到键值
public String getValues(String key){
return properties.getProperty(key);
}
}
package com.bdqn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 基类
* @author Administrator
*
*/
public class BaseDao {
public Connection connection=null;
public PreparedStatement ps=null;
//获取资源
public Connection getConnection(){
String driver = ConfigManager.getConfigManager().getValues(“driver”);
String url = ConfigManager.getConfigManager().getValues(“url”);
String user = ConfigManager.getConfigManager().getValues(“user”);
String pwd = ConfigManager.getConfigManager().getValues(“pwd”);
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
public void close(Connection connection,Statement st,ResultSet rs){
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (connection !=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//增删改
public int mySql(String sql,Object[] objs){
int num=0;
try {
connection = getConnection();
ps = connection.prepareStatement(sql);
if (objs !=null && objs.length>0) {
for (int i = 0; i < objs.length; i++) {
ps.setObject((i+1), objs[i]);
}
}
num = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
this.close(connection, ps, null);
}
return num;
}
//查询
public ResultSet getResultSet(String sql,Object[] objs){
ResultSet rs = null;
try {
connection = getConnection();
ps = connection.prepareStatement(sql);
if (objs != null && objs.length>0) {