Connecting to a database using JDBC

December 2016



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:


ClassesInterfacesExceptions
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:
Class.forName("name.of.class");

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.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Some compilers may refuse the above notation and you must call the driver as follows:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance;


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 CommentcaMarche.net.

Related :

This document entitled « Connecting to a database using JDBC » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.