偶然碰到这个需求,在各种百度下终于成功完成需求。第一次写博客,希望大家多多指教!
在开发过程中,我最开始的问题是如何用java程序连接远程数据库,为此百度了很久才成功连接上远程数据库。
而且需要需求是说不能在代码里写死远程数据库的地址,需要将数据源写在配置文件(db.properties)里。
db.properties内容如下:
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:ORCL
user=tzsb
password=tzsb
driver1=com.microsoft.sqlserver.jdbc.SQLServerDriver
url1=jdbc:sqlserver://远程数据库地址:端口号;DatabaseName=数据库名称
user1=数据库用户名
password1=数据库密码
因为需要操作两个不同的数据库,所以我在配置文件里写好了远程数据库和本地数据库的数据源信息。
在此需要一个工具类来读取这个配置文件db.properties里面的数据源信息。这个工具类是ReadProperties。
ReadProperties.java内容如下:
package com.wintime.db;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
static private String driver = null;
static private String url = null;
static private String user = null;
static private String password = null;
//因为需要操作远程和本地两个数据库,所以需要定义两种变量,下面的get方法同理
static private String driver1 = null;
static private String url1 = null;
static private String user1 = null;
static private String password1 = null;
static {
loads();
}
synchronized static public void loads() {
if (driver == null || url == null || user == null || password == null) {
InputStream is = ReadProperties.class.getResourceAsStream("/db.properties");
Properties dbproperties = new Properties();
try {
dbproperties.load(is);
driver = dbproperties.getProperty("driver").toString();
url = dbproperties.getProperty("url").toString();
user = dbproperties.getProperty("user&