1,jdbc.properties文件
driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:BDQN
username=wjb
password=wjb
2,读取properties文件
package cn.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigManager {
//读取jdbc.properties配置文件,单例模式
private static ConfigManager configManager;
private static Properties properties;
//单例模式必须用private构造方法,不能用public
private ConfigManager(){
String configFile = "jdbc.properties";
properties = new Properties();
InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
//提供一个入口获取ConfigManager,这个方法可以严格控制实例生成的个数
public static ConfigManager getInstance(){
//如果为空就创建一个自已的构造方法,获取ConfigManager
if(configManager == null){
configManager = new ConfigManager();
}
return configManager;
}
//以上只是获取了properties的KEY值,下面这个方法获取对应的value值
public String getString (String key){
return properties.getProperty(key);
}
}
3,连接数据库的基类
package cn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.pojo.Dancer;
import cn.util.ConfigManager;
public class BaseDao {
Connection connection = null;
ResultSet rs = null;
PreparedStatement pst = null;
//连接数据库的方法
public boolean getConnection(){
String driver = ConfigManager.getInstance().getString("driverClassName");
String url = ConfigManager.getInstance().getString("url");
String username = ConfigManager.getInstance().getString("username");
String password = ConfigManager.getInstance().getString("password");
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
//增删改
public int executeUpdate(String sql,Object[] param){
int row = 0;
if(this.getConnection()){
try {
pst = connection.prepareStatement(sql);
for(int i = 0;i<param.length;i++){
pst.setObject(i+1, param[i]);
}
row = pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return row;
}
//查询
public ResultSet executeQuery(String sql,Object[] param){
if(this.getConnection()){
try {
pst = connection.prepareStatement(sql);
for(int i=0;i<param.length;i++){
pst.setObject(i+1, param[i]);
}
rs = pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
}