Home

JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies


Connecting to a Database with JDBC

In order to work with a database from our JSP related code we need to create a connection. This is done by creating a connection object that can be used to perform any of the CRUD (create, read, update and delete) activities.

// Import the namespace for the database connection
import java.sql

// Create the database connection object
Connection cnDB = null;

// Load the driver that will be used for the database connection
Class.forName(”com.mysql.jdbc.Driver”).newInstance();

// Establish the connection
cnDB = DriverManager.getConnection(”jdbc:mysql:///DatabaseName”,”user”, “password”);

import java.sql
This line lets the system know that you will make references to objects pertaining to sql without having to use a complete namespace reference.

Connection cnDB = null;
In order to do any work with the database we will need a connection object. This line creates a connection object “cnDB” that we can use later in the code.

Class.forName()
Class.forName() uses reflection to dynamically load a class on runtime and register it with the DriverManager class. This allows you to load whatever driver will make sense for the database that you wish to connect to. For instance, to connect with an Oracle, DB2 or Postgre database you could use one of the following lines for your respective database

Class.forName (”oracle.jdbc.driver.OracleDriver”);
Class.forName(”com.ibm.db2.jdbc.app.DB2Driver”);
Class.forName(”postgresql.Driver”);

For our sample we will be connecting to a MySQL Database and will therefore use com.mysql.jdbc.Driver supplied by MySQL AB called Connector J. More information about Connector J can be found at:
http://www.mysql.com/products/connector/j/

cnDB = DriverManager.getConnection(”jdbc:mysql:///DatabaseName”,”user”, “password”);
The connection object is now given the information needed to connect with the database in the form of a URL. The URL can contain the database hostname, database name, user and password.

jdbc:mysql://databasehost/database?user=username&password=password

We will now be able to use this object to communicate with the database as the following illustrations will demonstrate.