net/print/219397
Introduction to JDBC
JDBC is an API that allows you to store, retrieve, and manipulate data in
virtually any data source, and to manipulate the data structures. Although the
JDBC 4.0 Specification proposal has been drafted, we will cover the current
version, JDBC 3.0, which is included in J2SE 1.4. This section explains the JDBC
object model and the most important classes and interfaces, to enable you to
develop database-based servlet and JSP applications. Here are the steps
required to access data in a database:
1 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
There are two packages in JDBC 3.0: java.sql and javax.sql. The java.sql package
is often referred to as the JDBC core API and is sufficient to do basic data
manipulations. The javax.sql package is the JDBC Optional Package API. It
provides additional features, including connection pooling, which I'll discuss in
another article. The following subsections will discuss the four most important
members of the java.sql package: the DriverManager class and the Connection, the
Statement, and the ResultSet interfaces.
JDBC drivers normally come in a .jar file. The first thing you need to do once
you have the driver is copy it into the WEB-INF\lib directory under your
application directory.
Then, from your servlet/JSP page, you use the DriverManager class to load JDBC
drivers. The JDBC driver must be located in the WEB-INF/lib directory under the
application directory. To load the JDBC driver, you use this code:
try {
Class.forName("JDBC.driver");
}
catch (ClassNotFoundException e) {
// driver not found
}
You will need to replace JDBC.driver with the fully qualified name of the JDBC
driver class. This name can be found in the documentation accompanying the
JDBC driver.
For example, for a MySQL database, the most popular driver is the one written
2 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
Class.forName("org.gjt.mm.mysql.Driver");
For an ODBC database, use the following code to load the driver:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Or, if you are using the FreeTds Type 4 JDBC driver to connect to a Microsoft
SQL Server, you use this code to load the driver:
Class.forName("com.internetcds.jdbc.tds.Driver");
jdbc:subprotocol:subname
The subprotocol and subname parts depend on the database server you use.
The documentation of the JDBC driver should tell you the subprotocol and the
subname to use.
For instance, if you are using a JDBC-ODBC bridge driver, the subprotocol is
"odbc" and the subname is the Data Source Name (DSN) for that database.
For instance, for a DSN called CompanySecret, your URL will be:
jdbc:odbc:CompanySecret
With a MySQL database, the subprotocol part is "mysql" and the subname part
should be given the name of the machine and the database. For example, for a
database named AdminStuff in a machine called xeon, use the following:
jdbc:mysql///xeon/AdminStuff
If the driver you load recognizes the URL in the getConnection method, it will
attempt to establish a connection with the database server.
3 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
Connection connection =
In the code above, "budi" is the user name and "secret" is the password for
user budi.
Once you're finished with the connection, you should close it to save resources
by calling the close method.
You use the Statement interface method to execute an SQL statement and obtain
the produced results. A Statement object is returned by the createStatement()
method of the Connection interface. Here is an example of how to create a
Statement object.
The two most important methods of this interface are executeQuery() and
executeUpdate(). The executeQuery() method executes an SQL statement that returns
a single ResultSet object. The executeUpdate() method executes an insert, update,
and delete SQL statement. The method returns the number of records affected
by the SQL statement execution.
4 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
"go." The driver you are using will automatically supply the appropriate
statement terminator, and you will not need to include it in your JDBC code.
The executeQuery() method executes an SQL SELECT statement that returns data.
This method returns a single ResultSet object, which is discussed next. The
ResultSet object contains the data produced by the given query. This method
never returns a null. For example, to create a table named Users with two
fields, you can use the following code:
statement.executeUpdate(sql);
Then, to add a record in the Users table, you use the following code:
statement.executeUpdate(sql);
You use the executeQuery() method when you expect a ResultSet object, as
described in the next section.
Other important methods are getXXX() methods, where XXX is the data type
returned by the method at the specified index, including String, long, and int.
The indexing used is 1-based. For example, to obtain the second column of
type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a
5 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
column index. For instance, the following code retrieves the value of the
column LastName of type String.
resultSet.getString("LastName");
The following example shows how you can use the next() method as well as the
getString() method. Here you retrieve the Address and PhoneNumber columns
from a table called Addresses. You then iterate through the returned ResultSet
and print all the address and phone number in the format "address|phone
number" to the console.
while (resultSet.next()) {
To summarize from the section above, You loaded the JDBC and returned a
Connection object. You used the Connection object to create a Statement object. You
then either updated the data or generated a ResultSet object.
Now, let's see how you can use JDBC to manipulate data in a database from a
JSP page.
This example uses the mm MySQL JDBC driver to access the Users table in a
MySQL Server database named CompanySecret. The database server is called
xeon and you need to pass the user name "budi" and password "secret" to log
into the database server. The SQL statement queries two columns: FirstName
and LastName. Upon retrieving the ResultSet, the statement will loop through it
to print all the first names and last names in the ResultSet.
In this example, I mix Java code with HTML to make the example simpler. In
real-world applications, you should always separate your Java code into a
JavaBean or a custom tag library.
<html>
6 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
<head>
<title>Accessing data in a database</title>
</head>
<body>
<%
try {
// Step 1. Load the JDBC driver
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("got connection");
Now, if you open your browser and type in the URL to the JSP page, you can
see the data from the database displayed on it, as shown in Figure 1. What
appears on your browser might be different than Figure 1, depending on what
7 of 8 01/24/2011 03:24 PM
Accessing Databases from Servlets and JSP Pages http://www.java.net/print/219397
Screen shot.
Figure 1. Displaying data from the database.
Summary
This article introduced JDBC and showed how you can manipulate data in a
relational database from your servlet or JSP page. For this purpose, you need to
use the four members of the java.sql package: DriverManager, Connection, Statement,
and ResultSet. Bear in mind, however, that this is only an introduction. To create
a scalable Web application, you need to dig more into JDBC to use advanced
features such as prepared statements and connection pooling.
Links:
[1] http://www.java.net/author/budi-kurniawan
[2] http://industry.java.sun.com/products/jdbc/drivers
[3] http://www.worldserver.com/mm.mysql/
8 of 8 01/24/2011 03:24 PM