servlets struts hibernate spring maven java
 

JDBC - Database Connections


After you've introduced the proper driver, the time has come to build up a database association utilizing JDBC.

The programming required to build up a JDBC association is genuinely basic. Here are these straightforward four stages −

  • Import JDBC Packages: Add import proclamations to your Java program to import required classes in your Java code.

  • Register JDBC Driver: This progression makes the JVM load the ideal driver usage into memory so it can satisfy your JDBC requests.

  • Database URL Formulation: This is to make an appropriately organized location that focuses to the database to which you wish to connect.

  • Create Connection Object: Finally, code a call to the DriverManager item's getConnection( ) technique to build up genuine database connection.

Import JDBC Packages

The Import proclamations advise the Java compiler where to discover the classes you reference in your code and are set at the earliest reference point of your source code.

To utilize the standard JDBC bundle, which enables you to choose, supplement, refresh, and erase information in SQL tables, include the accompanying imports to your source code −

import java.sql.* ; //for standard JDBC programs 

import java.math.* ; //for BigDecimal and BigInteger support

Register JDBC Driver

You must enlist the driver in your program before you use it. Enrolling the driver is the procedure by which the Oracle driver's class document is stacked into the memory, so it very well may be used as a usage of the JDBC interfaces.

You need to do this enrollment just once in your program. You can enroll a driver in one of two ways.

Approach I - Class.forName()

The most normal way to deal with register a driver is to utilize Java's Class.forName() strategy, to powerfully stack the driver's class document into memory, which naturally enrolls it. This technique is ideal since it enables you to make the driver enrollment configurable and portable.

The following model uses Class.forName( ) to enlist the Oracle driver −

try { 

Class.forName("oracle.jdbc.driver.OracleDriver"); 

} 

catch(ClassNotFoundException ex) { 

System.out.println("Error: powerless to stack driver class!"); 

System.exit(1); 

}

You can utilize getInstance() technique to work around resistant JVMs, yet then you'll need to code for two additional Exceptions as pursues −

try { 

Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 

} 

catch(ClassNotFoundException ex) { 

System.out.println("Error: helpless to stack driver class!"); 

System.exit(1); 

catch(IllegalAccessException ex) { 

System.out.println("Error: get to issue while loading!"); 

System.exit(2); 

catch(InstantiationException ex) { 

System.out.println("Error: helpless to instantiate driver!"); 

System.exit(3); 

}

Approach II - DriverManager.registerDriver()

The second methodology you can use to enroll a driver, is to utilize the static DriverManager.registerDriver() method.

You should utilize the registerDriver() strategy in the event that you are utilizing a non-JDK agreeable JVM, for example, the one given by Microsoft.

The following precedent uses registerDriver() to enlist the Oracle driver −

try { 

Driver myDriver = new oracle.jdbc.driver.OracleDriver(); 

DriverManager.registerDriver( myDriver ); 

} 

catch(ClassNotFoundException ex) { 

System.out.println("Error: helpless to stack driver class!"); 

System.exit(1); 

}

Database URL Formulation

After you've stacked the driver, you can build up an association utilizing the DriverManager.getConnection() strategy. For simple reference, let me list the three over-burden DriverManager.getConnection() strategies −

  • getConnection(String url)

  • getConnection(String url, Properties prop)

  • getConnection(String url, String client, String password)

Here each structure requires a database URL. A database URL is a location that focuses to your database.

Formulating a database URL is the place the majority of the issues related with setting up an association occurs.

Following table records down the well known JDBC driver names and database URL.

RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName

All the featured part in URL group is static and you have to change just the rest of the part according to your database setup.

Create Connection Object

We have recorded down three types of DriverManager.getConnection() strategy to make an association object.

Using a Database URL with a username and password

The most regularly utilized type of getConnection() expects you to pass a database URL, a username, and a password:

Assuming you are utilizing Oracle's thin driver, you'll determine a host:port:databaseName esteem for the database segment of the URL.

If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle audience is designed to tune in on port 1521, and your database name is EMP, at that point total database URL would be −

jdbc:oracle:thin:@amrood:1521:EMP

Now you need to call getConnection() strategy with suitable username and secret phrase to get a Connection object as pursues −

String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; 

String USER = "username"; 

String PASS = "password" 

Connection conn = DriverManager.getConnection(URL, USER, PASS);

Using Only a Database URL

A second type of the DriverManager.getConnection( ) strategy requires just a database URL −

DriverManager.getConnection(String url);

However, for this situation, the database URL incorporates the username and secret key and has the accompanying general structure −

jdbc:oracle:driver:username/password@database

So, the above association can be made as pursues −

String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP"; 

Connection conn = DriverManager.getConnection(URL);

Using a Database URL and a Properties Object

A third type of the DriverManager.getConnection( ) technique requires a database URL and a Properties object −

DriverManager.getConnection(String url, Properties info);

A Properties object holds a lot of catchphrase esteem sets. It is utilized to pass driver properties to the driver amid a call to the getConnection() method.

To make a similar association made by the past models, utilize the accompanying code −

import java.util.*; 

String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; 

Properties data = new Properties( ); 

info.put( "user", "username" ); 

info.put( "password", "password" ); 

Connection conn = DriverManager.getConnection(URL, info);

Closing JDBC Connections

At the finish of your JDBC program, it is required unequivocally to close every one of the associations with the database to end every database session. Be that as it may, if you overlook, Java's trash specialist will close the association when it tidies up stale objects.

Relying on the refuse gathering, particularly in database writing computer programs, is an extremely poor programming practice. You should make a propensity for continually shutting the association with the nearby() strategy related with association object.

To guarantee that an association is shut, you could give an 'at long last' hinder in your code. A finally square dependably executes, paying little heed to a special case happens or not.

To close the above opened association, you should call close() technique as pursues −

conn.close();

Explicitly shutting an association rations DBMS assets, which will make your database overseer happy.

For a superior comprehension, we recommend you to think about our JDBC - Sample Code tutorial.







© Javacodegeeks © 2019 - 2019
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3