通用的JDBC连接实现
思路:配置文件配置数据库信息,工具类根据配置的信息到相应的数据库连接对象。同等条件下,数据源获取连接优先。
实现:
一、工具类
/**
* 通用数据库连接工厂
*/
public class DBUtil {
private static String driver;
private static String dburl;
private static String dbname;
private static String user;
private static String password;
private static String datasource;
private static final ConnectionFactory factory = new ConnectionFactory();
private Connection conn;
static {
Properties prop = new Properties();
try {
InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("dbconfig.properties");
prop.load(in);
} catch (Exception e) {
System.out.println("IO读取出错,找不到dbconfig.properties!");
}
datasource = prop.getProperty("datasource", "");
driver = prop.getProperty("driver");
dburl = prop.getProperty("dburl", "");
user = prop.getProperty("user", "");
password = prop.getProperty("password", "");
datasource = prop.getProperty("datasource", "");
//log.info("获取dbconfig.properties信息:driver=" + driver + "dburl=" + dburl + "
" + "dbname=" + dbname + "
" + "user=" + user + "
" + "password=" + password + "
"