Java Reference
In-Depth Information
7. Perform Steps 7-9 of Section 24.5.1 to create the addressbook database. In each
step, replace books with addressbook .
You're now ready to execute this chapter's examples.
24.5.3 Creating the Chapter's Databases on Linux
After setting the JAVA_HOME environment variable, perform the following steps:
1. Open a shell window.
2. Perform the steps in Section 24.5.2, but in Step 1, set DERBY_HOME to
DERBY_HOME= YourLinuxJDKInstallationFolder /db
On our Ubuntu Linux system, this was:
DERBY_HOME=/usr/lib/jvm/java-7-oracle/db
You're now ready to execute this chapter's examples.
24.6 Manipulating Databases with JDBC
This section presents two examples. The first introduces how to connect to a database and
query it. The second demonstrates how to display the result of the query in a JTable .
24.6.1 Connecting to and Querying a Database
The example of Fig. 24.23 performs a simple query on the books database that retrieves
the entire Authors table and displays the data. The program illustrates connecting to the
database, querying the database and processing the result. The discussion that follows pres-
ents the key JDBC aspects of the program.
Lines 3-8 import the JDBC interfaces and classes from package java.sql used in this
program. Method main (lines 12-48) connects to the books database, queries the database,
displays the query result and closes the database connection. Line 14 declares a String
constant for the database URL. This identifies the name of the database to connect to, as
well as information about the protocol used by the JDBC driver (discussed shortly). Lines
15-16 declare a String constant representing the SQL query that will select the authorID ,
firstName and lastName columns in the database's authors table.
1
// Fig. 24.23: DisplayAuthors.java
2
// Displaying the contents of the Authors table.
3
import java.sql.Connection;
4
import java.sql.Statement;
5
import java.sql.DriverManager;
6
import java.sql.ResultSet;
7
import java.sql.ResultSetMetaData;
8
import java.sql.SQLException;
9
10
public class DisplayAuthors
11
{
Fig. 24.23 | Displaying the contents of the Authors table. (Part 1 of 2.)
 
 
 
 
Search WWH ::




Custom Search