The DriverManager.getConnection makes call to driver.connect() internally to get database connection.
Are there any pitfalls of using driver.connect() directly?
java.sql.Driver is an interface, you need an actual implementation (eg org.firebirdsql.jdbc.FBDriver for Firebird) to actually do anything with it. On the other hand, DriverManager is a concrete class that abstracts (hides) driver loading, selection and usage for you.
Normally you should not use a Driver implementation directly. Stick with either using DriverManager, or otherwise use a DataSource implementation (preferably through configuration).
Using DriverManager decouples your code from the actual driver used. That means you do not have a compile time dependency on a specific driver. Changing drivers or even database system (assuming the SQL is compatible or generated compatibly) is then just a manner of adding/replacing a driver jar on the class path and specifying the right JDBC url in the configuration. That is assuming JDBC 4 automatic driver loading, otherwise adding the specific driver name to the config and using Class.forName(<value from config>) is also necessary.
For example, for SQL Server you have the driver from Microsoft or the jTDS driver (+ other third party drivers). Switching between those is - basically - a matter of adding the right driver to the class path and changing the URL in the configuration.
In the past, Microsoft even had a breaking change in their JDBC driver, changing both the class name of the driver and the URL. If you had hard coded a dependency on the Driver implementation, your code would break if you tried to upgrade the driver. If you had just used DriverManager (and had a config option for the URL, and - this was before automatic driver loading - the driver class name for loading), things would just have continued to work after a configuration change.
There are exceptions where you would use a Driver implementation directly (usually through reflection and still not hard coded), but those situations are rare, and unless you have a very good reason (and know what you're doing) then just don't do that.
Related
I have a library method that can be used to connect to a database and then build a document using data from the database.
When they run this app with no parameters, I want to list out all available sql vendor connections. Based on this question I'm guessing its done using ServiceLoader but it's not clear to me exactly how to do this.
And critical to this is I'd like to get the class "com.mysql.jdbc.Driver", and I must get the "jdbc:mysql:" start of the connection string syntax.
So, how can I get the class (optional) and connection string start (necessary) of all JDBC connectors in the classpath?
There is no way defined in JDBC to automatically discover the JDBC URL format of a driver.
You will need to keep a registry of JDBC URL formats yourself (eg linked to one or more drivers), and then using the ServiceLoader or DriverManager, discover the available drivers and use that to determine which URL formats you can use.
Be aware that JDBC allows multiple drivers to use the same JDBC URL format (the first driver to successfully connect 'wins'), and a single driver can have more than one JDBC URL format.
To discover the JDBC drivers on the classpath, you can use
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
for (Driver driver : loadedDrivers) {
// do something with Driver
}
Be aware that using for-each might not be the best solution. Explicitly using the iterator might be better as then you can explicitly handle the ServiceConfigurationError thrown if a specific driver fails to load.
Alternatively, you can use
Enumeration<Driver> drivers = DriverManager.getDrivers();
And let DriverManager take care of discovering the drivers.
Maybe you can use a framework, which abstracts the layer of data access i.e. all the talking to the database?
I could recommend you Spring Data JDBC. https://spring.io/projects/spring-data-jdbc
But there are more frameworks that you could find as OR-Mapper which could help you.
I understand that class loading is useful for load the class at runtime with its class name.
However while using JDBC in our project we know which driver we are going to use and mostly driver manager string is hard coded.
My question is: Why are we loading driver using Class.forName("JDBC_DRIVER") here?
Why can't we go ahead adding the driver in class path? since we know which driver jar we are going to use.
I believe Class.forName(JDBC_DRIVER) will load the Driver into DriverManager. Is it the only reason?
Edit 1:
The DriverManager API doc states that
As part of its(DriverManager) initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property.
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Then when I use other than oracle driver; do I need to change the driver name string in system property?
First of: with modern JDBC drivers and a current JDK (at least Java 6) the call to Class.forName() is no longer necessary. JDBC driver classes are now located using the service provider mechanism. You should be able to simply remove that call and leave the rest of the code unchanged and it should continue to work.
If you're not using a current JDK (or if you have a JDBC driver that does not have the appropriate files set up to use that mechanism) then the driver needs to be registered with the DriverManager using registerDriver. That method is usually called from the static initializer block of the actual driver class, which gets triggered when the class is first loaded, so issuing the Class.forName() ensures that the driver registers itself (if it wasn't already done).
And no matter if you use Class.forName() or the new service provider mechanism, you will always need the JDBC driver on the classpath (or available via some ClassLoader at runtime, at least).
tl;dr: yes, the only use of that Class.forName() call is to ensure the driver is registered. If you use a current JDK and current JDBC drivers, then this call should no longer be necesary.
The Class.forName(JDBC_DRIVER) call will register your JDBC driver in the DriverManager, so you can address it by url, such as "jdbc:odbc:Database" and so on...
Usually the driver class has static initialization code like this, which is invoked on Class.forName():
public class Driver implements java.sql.Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
}
You still have to put JDBC driver jar into the classpath.
As an alternative, you can use database specific DataSource, then you can declaratively specify the datasource type, for example in Spring context or in your Web server JNDI. Here is an example.
Putting a class in the classpath is not sufficient to have it loaded by the class loader. And the driver class must be loaded to ensure that it's registered to the JDBC API. BTW, for Class.forName to work, the driver class must be in the classpath.
In many industrial applications, we would like to abstract the data access layer from the rest of code, by pulling such information in a form of a property file/configuration file. In those cases, we might need to use something as you have done.
For e.g. we can use the JDBC interface classes to write the code to access the database, where you could configure the properties by selecting which technology you want to use as a database (e.g. ojdbc driver, or mysql jdbc driver, etc.) In those cases you can load the class using such method.
I've read here on SO that since java 6 you no longer need to register JDBC Driver using:
Class.forName(JDBC_DRIVER);
because DriverManager uses the path located in system property "jdbc.drivers"
to retrieve the correct driver.
But when I do the followng:
System.out.print(System.getProperty("jdbc.drivers"));
null gets printed.
Do you have any clue why my app works correctly ?? ;)
That has nothing to do with that system property. Java6 (and JDBC4) introduced a concept known as "service provider" where implementations of known interface can be detected by the JVM during startup. A driver that is compliant with that will be registered by the DriverManager automatically. That's why Class.forName() is no longer necessary - but only if the driver supports that.
The service registration is initiated if there is a services directory in the driver's jar file inside the META-INF directory. That directory needs to contain a text file with the name of the interface that is implemented in the case of a JDBC driver that is java.sql.Driver containing the implementing class.
From the Javadocs of DriverManager:
As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications. For example in your ~/.hotjava/properties file you might specify:
jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver
This means that the system property need not be specified (as it says DriverManager will attempt). There is another mechanism through which drivers are automatically loaded, which relies on service loading since Java 6:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver.
Almost all JDBC drivers now conform to this requirement. Note that DriverManager does not internally fill the jdbc.drivers property, so it's still null.
I understand that class loading is useful for load the class at runtime with its class name.
However while using JDBC in our project we know which driver we are going to use and mostly driver manager string is hard coded.
My question is: Why are we loading driver using Class.forName("JDBC_DRIVER") here?
Why can't we go ahead adding the driver in class path? since we know which driver jar we are going to use.
I believe Class.forName(JDBC_DRIVER) will load the Driver into DriverManager. Is it the only reason?
Edit 1:
The DriverManager API doc states that
As part of its(DriverManager) initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property.
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Then when I use other than oracle driver; do I need to change the driver name string in system property?
First of: with modern JDBC drivers and a current JDK (at least Java 6) the call to Class.forName() is no longer necessary. JDBC driver classes are now located using the service provider mechanism. You should be able to simply remove that call and leave the rest of the code unchanged and it should continue to work.
If you're not using a current JDK (or if you have a JDBC driver that does not have the appropriate files set up to use that mechanism) then the driver needs to be registered with the DriverManager using registerDriver. That method is usually called from the static initializer block of the actual driver class, which gets triggered when the class is first loaded, so issuing the Class.forName() ensures that the driver registers itself (if it wasn't already done).
And no matter if you use Class.forName() or the new service provider mechanism, you will always need the JDBC driver on the classpath (or available via some ClassLoader at runtime, at least).
tl;dr: yes, the only use of that Class.forName() call is to ensure the driver is registered. If you use a current JDK and current JDBC drivers, then this call should no longer be necesary.
The Class.forName(JDBC_DRIVER) call will register your JDBC driver in the DriverManager, so you can address it by url, such as "jdbc:odbc:Database" and so on...
Usually the driver class has static initialization code like this, which is invoked on Class.forName():
public class Driver implements java.sql.Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
}
You still have to put JDBC driver jar into the classpath.
As an alternative, you can use database specific DataSource, then you can declaratively specify the datasource type, for example in Spring context or in your Web server JNDI. Here is an example.
Putting a class in the classpath is not sufficient to have it loaded by the class loader. And the driver class must be loaded to ensure that it's registered to the JDBC API. BTW, for Class.forName to work, the driver class must be in the classpath.
In many industrial applications, we would like to abstract the data access layer from the rest of code, by pulling such information in a form of a property file/configuration file. In those cases, we might need to use something as you have done.
For e.g. we can use the JDBC interface classes to write the code to access the database, where you could configure the properties by selecting which technology you want to use as a database (e.g. ojdbc driver, or mysql jdbc driver, etc.) In those cases you can load the class using such method.
Which is the difference from forName method vs registerDriver to load and register a JDBC driver?
Class.forName() is not directly related to JDBC at all. It simply loads a class.
Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().
registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).
Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:
my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.
DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.
In additaion to what Joachim Sauer already mentioned about JDBC 4 drivers, note that in practice you usually want to inject either an EntityManager (JPA) or a pooled DataSource (and use JdbcTemplate of Spring).