Connecting to a database using JDBC

Jose Simpton

The JDBC API (Application Programming Interface), that is to say, the JDBC class library, initiates connection a database in 3 steps:

Create a database connection

Sending SQL statements

Process results from the database

The java.sql.* package

All objects and methods related to the databases are present in the java.sql.* package. It is therefore necessary to import java.sql.* in programs making use of the JDBC technology.

The java.sql package contains the following items:

Classes Interfaces Exceptions Date

DriverManager

DriverPropertyInfo

Time

Timestamp

Types Array

Blob

CallableStatement

Clob

Connection

DatabaseMetaData

Driver

PreparedStatement

Ref

ResultSet

ResultSetMetaData

SQLData

SQLInput

SQLOutput

Statement

Struct BatchUpdateException

DataTruncation

SQLException

SQLWarning

Connecting to the database

To connect to a database it is essential to initially load the related driver using the DriverManager:

ClasorName("namelass");

This instruction loads the driver and creates an instance of this class. To connect to a database declared within the ODBC Administrator for example, you will need to load the JDBC-ODBC bridge driver:

driver.ClasorName("sun.jdbcdbc.JdbcOdbcDriver");

Some compilers may refuse the above notation and you must call the driver as follows:

ClasorName("sun.jdbcdbc.JdbcOdbcDriverewInstance;

To connect to a particular database, you will need to create an instance of the Connection class through the getConnection method of the DriverManager object, specifying the database to be loaded using the URL

String url = "jdbc:odbc:dbname"; Connection con = DriverManager.getConnection(url);

The name of the database (dbname) is the one declared in the ODBC control panel. The URL syntax may vary slightly depending on the type of database. The syntax is as follows:

jdbc:subprotocol:name

Original document published on CommentcaMarcheet.