最近一直在负责动态数据源的问题,做一个统一的接口适配,今天在做一个连接时,会有一个测试连接的过程
Class.forName(driver);
connnection = DriverManager.getConnection(dbUrl, user, password);
driver代表的数据库驱动,发现测试连接时是OK的,但是真正的配置成为数据源时却出现了问题。
后来发现,我用的是 com.mysql.jdbc.Driver mysql的驱动,但是数据库是一个oracle的数据库,找到了问题所在,问题也解决了,但是为什么会出现这种问题了。
后面去看了DriverManager.getConnection的源码发现
for(DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerCL)) {
try {
println(" trying " + aDriver.driver.getClass().getName());
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
// Success!
println("getConnection returning " + aDriver.driver.getClass().getName());
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println(" skipping: " + aDriver.getClass().getName());
}
}
可以看到它是从一个driver集合里面取出driver去试探性的链接,而我们做动态数据源的时候是有注册oracle的驱动的,所以用这个方法,你的驱动写的mysql,但是它返回成功是因为它使用了oracle的驱动。
所以该测试连接在配置动态数据源,配置datasourse时是不对的,应该改为获取对应的数据库驱动去尝试连接,如果连接不为空,才是正确的。
Driver driverClass = (Driver) Class.forName(driver).newInstance();
// 获取连接
Properties info = new Properties();
if(!StringUtils.isEmpty(user)){
info.put("user", user);
}
if(!StringUtils.isEmpty(password)){
info.put("password", password);
}
connnection = driverClass.connect(dbUrl, info);
//connnection = DriverManager.getConnection(dbUrl, user, password);
if(connnection!=null){
result = true;
}else{
throw new Exception("数据库驱动不匹配,请修改为正确的数据库驱动");
}
从这里看出来,我们遇到问题的时候可以深入去看看它的源码,从源码你就会知道你的问题具体在哪。