Java DriverManager Always Assigns My Driver
Posted
by JGB146
on Stack Overflow
See other posts from Stack Overflow
or by JGB146
Published on 2010-04-20T21:09:11Z
Indexed on
2010/04/20
21:13 UTC
Read the original article
Hit count: 243
I am writing a driver to act as a wrapper around two separate MySQL connections (to distributed databases). Basically, the goal is to enable interaction with my driver for all applications instead of requiring the application to sort out which database holds the desired data.
Most of the code for this is in place, but I'm having a problem in that when I attempt to create connections via the MySQL Driver, the DriverManager is returning an instance of my driver instead of the MySQL Driver. I'd appreciate any tips on what could be causing this and what could be done to fix it!
Below is a few relevant snippets of code. I can provide more, but there's a lot, so I'd need to know what else you want to see.
First, from MyDriver.java:
public MyDriver() throws SQLException
{
DriverManager.registerDriver(this);
}
public Connection connect(String url, Properties info)
throws SQLException
{
try { return new MyConnection(info); }
catch (Exception e) { return null; }
}
public boolean acceptsURL(String url)
throws SQLException
{
if (url.contains("jdbc:jgb://"))
{ return true; }
return false;
}
It is my understanding that this acceptsURL function will dictate whether or not the DriverManager deems my driver a suitable fit for a given URL. Hence it should only be passing connections from my driver if the URL contains "jdbc:jgb://" right?
Here's code from MyConnection.java:
Connection c1 = null;
Connection c2 = null;
/**
*Constructors
*/
public DDBSConnection (Properties info)
throws SQLException, Exception
{
info.list(System.out); //included for testing
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url1 = "jdbc:mysql://server1.com/jgb";
String url2 = "jdbc:mysql://server2.com/jgb";
this.c1 = DriverManager.getConnection(
url1, info.getProperty("username"), info.getProperty("password"));
this.c2 = DriverManager.getConnection(
url2, info.getProperty("username"), info.getProperty("password"));
}
And this tells me two things. First, the info.list() call confirms that the correct user and password are being sent. Second, because we enter an infinite loop, we see that the DriverManager is providing new instances of my connection as matches for the mysql URLs instead of the desired mysql driver/connection.
FWIW, I have separately tested implementations that go straight to the mysql driver using this exact syntax (al beit only one at a time), and was able to successfully interact with each database individually from a test application outside of my driver.
© Stack Overflow or respective owner