Database Connection Using JDBC To Java Application Note
Database Connection Using JDBC To Java Application Note
Database Connection Using JDBC To Java Application Note
Application Note:
Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
To use the standard JDBC package, which allows you to select, insert, update,
and delete data in SQL tables, add the following imports to your source code
−
You need to do this registration only once in your program. You can register
a driver in one of two ways.
Approach I - Class.forName()
The most common approach to register a driver is to use
Java's Class.forName() method, to dynamically load the driver's class file
into memory, which automatically registers it. This method is preferable
because it allows you to make the driver registration configurable and
portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch(ClassNotFoundException ex) {
System.exit(1);
You can use getInstance() method to work around noncompliant JVMs, but
then you'll have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
catch(ClassNotFoundException ex) {
System.exit(1);
catch(IllegalAccessException ex) {
catch(InstantiationException ex) {
System.exit(3);
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK
compliant JVM, such as the one provided by Microsoft.
try {
DriverManager.registerDriver( myDriver );
catch(ClassNotFoundException ex) {
System.exit(1);
getConnection(String url)
Following table lists down the popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only
the remaining part as per your database setup.
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and
password to get a Connection object as follows −
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password
and has the following general form −
jdbc:oracle:driver:username/password@database
import java.util.*;
To close the above opened connection, you should call close() method as
follows −
conn.close();