通过编写properties配置文件对数据库url、username、userpwd进行配置,来连接oracle数据库。
方便数据库连接变更。
第一步:在src目录下创建db.properties配置文件
(配置文件内容以 key-value/键值对的形式存放)
driver =oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=user1
password=123456
第二步:在com.wu.service包下创建ConfigManager.class类
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//ConfigManager类
public class ConfigManager {
private static ConfigManager configManager;
private static Properties properties;
private ConfigManager() {
String configFile = "db.properties";
properties = new Properties();
//类.class:获取当前类的class对象,即“类的类”
//.getClassLoader():获取类加载器,从类的字符文件
InputStream in = ConfigManager.class.getClassLoader()
.getResourceAsStream(configFile);
try {
properties.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//单例模式:采用static修饰构造方法,整个项目运行中只有一个ConfigManager实例,所有方法调用的ConfigManager都是同一个
public static ConfigManager getInstance() {
//
if (configManager == null) {
configManager = new ConfigManager();
}
return configManager;
}
//传入key,通过Properties.getProperty(Stirng key)方法获取key对应的value值
public String getValue(String key) {
return properties.getProperty(key);
}
}
//建立连接Connection
public void getConn() throws ClassNotFoundException, SQLException {
String driver = ConfigManager.getInstance().getValue(
"jdbc.driver_class");
String url = ConfigManager.getInstance()
.getValue("url");
String userName = ConfigManager.getInstance().getValue(
" username");
String password = ConfigManager.getInstance().getValue(
" password");
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
}