Skip to content
Advertisement

How do I manually configure a DataSource in Java?

I’m trying to follow Sun’s JDBC tutorial at http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html

It gives the following example code:

DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");

Connection con = ds.getConnection();

This code doesn’t compile because the DataSource interface has none of these methods, except for the getConnection() method invoked last.

(Here’s the javadoc: http://java.sun.com/javase/6/docs/api/javax/sql/DataSource.html)

What am I missing?

Edit: I’m actually trying to connect to MySQL (com.mysql.jdbc) and I can’t find the javadoc for that. I’ll accept an answer that points me to either:

1) documentation for com.mysql.jdbc regarding a DataSource that I can understand, or

2) gives an example to follow for what the tutorial’s code should be, for any database.

Advertisement

Answer

Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

 DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

 String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

 Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here.

EDIT: One more thought, technically just having a line of code which does Class.forName(“com.mysql.jdbc.Driver”) should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn’t, so if you aren’t sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement