11
JDBC Database Connectivity JDBC Database Connectivity To utilize the JDBC functionality, one must directly interact with the operating system; thus, there is a certain amount of system configuration that one must complete. The application we develop here presents code to interact with a Microsoft Access database 1. Creating the Database & DSN Connection Before writing the actual application code, one should first ensure/create the database to be used. There are really no constraints to which database implementation one can use. You can choose any operating system and/or database that support Java technology. The primary difference when using another platform solution is in the way in which the driver and operating system connections are completed. The Java code should not vary except in the string that loads the driver. Creating the Microsoft Access Database The design of your database is quite simple and represents a small baseball equipment operation. The database will contain four fields: ID, Name, Price, and Quantity, as illustrated in Table 1. ID Name Price Quantity 1 Baseball $2.00 200 2 Bat $20.00 20 3 Glove $80.00 0 4 Catcher’s Glove $100.00 1 Table 1 The above table is created in Access. To do this, launch Microsoft Access and create a blank database called purchaseOrder.mdb. After you specify the name of the database as purchaseOrder.mdb, you then need to create the single table named By:Ritika Wason 1

A JDBC Tutorial

Embed Size (px)

Citation preview

Page 1: A JDBC Tutorial

JDBC Database Connectivity

JDBC Database Connectivity

To utilize the JDBC functionality, one must directly interact with the operating system; thus, there is a certain amount of system configuration that one must complete. The application we develop here presents code to interact with a Microsoft Access database

1. Creating the Database & DSN Connection

Before writing the actual application code, one should first ensure/create the database to be used. There are really no constraints to which database implementation one can use. You can choose any operating system and/or database that support Java technology. The primary difference when using another platform solution is in the way in which the driver and operating system connections are completed. The Java code should not vary except in the string that loads the driver.

Creating the Microsoft Access Database

The design of your database is quite simple and represents a small baseball equipment operation. The database will contain four fields: ID, Name, Price, and Quantity, as illustrated in Table 1.

ID Name Price Quantity

1 Baseball $2.00 200

2 Bat $20.00 20

3 Glove $80.00 0

4 Catcher’s Glove $100.00 1

Table 1

The above table is created in Access. To do this, launch Microsoft Access and create a blank database called purchaseOrder.mdb. After you specify the name of the database as purchaseOrder.mdb, you then need to create the single table named Transaction that we utilize in this example. After you enter all of the data in the table you designed, your database should as above.

2. Making the DSN Connection

Now that the database is complete, there is one more step you need to take to ensure the Java application you develop can make a connection to it. This step is highly dependent on the platform that you are using. In this example, you need to make a Data Source name (DSN) connection to the database. This is the mechanism that allows the application to connect to the database itself.

By:Ritika Wason 1

Page 2: A JDBC Tutorial

JDBC Database Connectivity

To accomplish this, first bring up the Control Panel from the start menu and then click on the Administrative Tools icon. In the Administrative Tools dialog box, click on the Data Sources icon.

3. Connecting to a Database with JDBCClicking on the Data Sources icon will bring you to the ODBC Data Source Administrator (see Figure 1) that will allow you to specify the name and the driver to be used by the application.

Figure 1 ODBC Data Source Administrator

Once in the ODBC Data Source Administrator, click on the File DSN tab and click on the Add button. The Microsoft ODBC Access Setup dialog box appears next as in Figure 2.

Figure 2

By:Ritika Wason 2

Page 3: A JDBC Tutorial

JDBC Database Connectivity

There are two things that must be completed in this dialog box:

1. Create a Data Source Name. 2. Click on the Select button and literally find the purchaseOrder.mdb file that you

previously created, as shown in Figure 3.

Figure 3

At this point the DSN connection is complete and you can proceed to the second part of developing the code to utilize the database and the DSN connection that you created.

4 Developing the Java/JDBC Application

With the DSN defined, you now can begin to develop the code to interact with the purchaseOrder database. To accomplish this, I have created two classes for the project. The first is the application called JDBCTest.java, which contains the main method; and the second is called RunDB.java, which neatly provides all of the functionality that you are interested in for this simple example. In short, the RunDB class contains methods that encapsulate the behaviors that you want to demonstrate. The mission now is simple: You want to cover the following topics:

1. Loading the database driver 2. Connecting to the DSN

3. Building a statement

4. Executing a query

You can start by developing the RunDB class. The structure of the class is very simple. You must import the java.sql.* package to allow you access to the package that contains the JDBC code. You also must provide two class attributes of type Connection and Statement. As the names

By:Ritika Wason 3

Page 4: A JDBC Tutorial

JDBC Database Connectivity

imply, you will use these attributes to store the connection and statement information. Access to these attributes is required by more than one method; thus, you need to define them for the scope of the class the framework for the RunDB class that is shown in Listing 1.

//RunDBimport java.sql.*;

public class RunDB {

Connection connection; Statement statement;

... behaviors

}

Listing 1

5 Loading the Database Driver

The first piece of functionality that you need to address is loading the JDBC driver for the specific platform by creating a method called loadDriver( ). In this case, you will load the ODBC/JDBC bridge by passing a string through the Class.forname( ) command as seen in Listing 2.

// Load the Driver

public void loadDriver() throws ClassNotFoundException{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}

Listing 2

Note: All of the methods in this class will throw the ClassNotFoundException exception. At this point in the development of the application, it is easier to catch all of the exceptions at the application level and not deal with them separately in each method.If successful, this class will load the driver provided by the Java implementation:

sun.jdbc.odbc.JdbcOdbcDriver.

6 Connecting to the DSN

Once the driver is loaded, the next order of business is to make the connection to the DSN, and thus the purchaseOrder database that you created earlier. You create a method called

By:Ritika Wason 4

Page 5: A JDBC Tutorial

JDBC Database Connectivity

makeConnection( ) and use the DriverManager class and its getConnection( ) method, as seen in Listing 3.

// Make the Connectionpublic void makeConnection() throws SQLException { connection=DriverManager.getConnection("jdbc:odbc:purchaseOrder"); Listing 3Note: The syntax specifies the name of the DSN, and not the purchaseOrder.mdb file itself. An error will be generated at this point if the DSN was not completed properly or if the database is not in its proper place. If everything works, you are now ready to do some actual SQL code.

7 Building a Statement & Executing a Query

In this case, you will issue an SQL select statement that will select all of the records from the transaction table.

SELECT * FROM Transaction

You create a method called executeQuery ( ) and use the Statement class and its execute ( ) method to initiate the SQL select statement that you want.

boolean foundResults = statement. execute ("SELECT * FROM Transaction");

If the statement execution is successful, you retrieve the result set with the following code:

ResultSet set = statement.getResultSet();

With the result set captured, you then can output the results via a method you supply, called displayResults ( ). Listing 4 shows the entire executeQuery ( ) method.

// Execute the querypublic void executeQuery() throws SQLException {

boolean foundResults = statement.execute("SELECT * FROM Transaction"); if(foundResults){ ResultSet set = statement.getResultSet(); if(set!=null) displayResults(set); }else { connection.close(); }}

Listing 4

By:Ritika Wason 5

Page 6: A JDBC Tutorial

JDBC Database Connectivity

The displayResults( ) method is simply a loop that iterates through the ResultSet. One of the interesting issues is how you can capture the metadata as well as the data itself. Remember that metadata is actually data that describes data. The metadata contains such information as the number of columns and the column names. You use the ResultSetMetaData class to capture the metadata. Then, you can use methods such as the ResultSetMetaData class's getColumnCount( ) method.

8 Connecting to a Database with JDBCYou create a single string that you will use to append all information that you want to output. That string can be written to either the screen or a file. To make things more interesting, you can create a document with XML-like tags using the column name as the tag names. You will use this technique in future columns when you learn about XML parsing. An XML tag would look like this:

<Name>Baseball</Name>

Listing 5 shows the complete displayResults( ) method.

// Display the Resultsvoid displayResults(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columns=metaData.getColumnCount(); String text="";

while(rs.next()){ for(int i=1;i<=columns;++i) { text+="<"+metaData.getColumnName(i)+">"; text+=rs.getString(i); text+="</"+metaData.getColumnName(i)+">"; text+="n"; } text+="n"; } System.out.println(text);}

Listing 5

Considering the powerful functionality that you have covered, there really is not that much code involved. Although hard coding the SQL statement is obviously not extensible, you can use this technique to verify that you have successfully connected and interacted with the database. The complete code for this application is presented in Listing 6. When we run this application and successfully connect to the purchaseOrder database, the output in Figure 4 is produced. Note that it is in pseudo XML-like tags.

By:Ritika Wason 6

Page 7: A JDBC Tutorial

JDBC Database Connectivity

// JDBC|Test – complete codepublic class JDBCTest {

public static void main(String args[]){

RunDB runDB = new RunDB();

try{ runDB.loadDriver(); runDB.makeConnection(); runDB.buildStatement(); runDB.executeQuery(); }catch(Exception e){ e.printStackTrace(); }

}}

//RunDBimport java.sql.*;

public class RunDB {

Connection connection; Statement statement;

public void loadDriver() throws ClassNotFoundException{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }

public void makeConnection() throws SQLException { connection= DriverManager.getConnection("jdbc:odbc:purchaseOrder") }

public void buildStatement() throws SQLException { statement = connection.createStatement(); }

public void executeQuery() throws SQLException {

boolean foundResults = statement.execute("SELECT * FROM Transaction"); if(foundResults){

By:Ritika Wason 7

Page 8: A JDBC Tutorial

JDBC Database Connectivity

ResultSet set = statement.getResultSet(); if(set!=null) displayResults(set); }else { connection.close(); } }

void displayResults(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columns=metaData.getColumnCount(); String text="";

while(rs.next()){ for(int i=1;i<=columns;++i) { text+="<"+metaData.getColumnName(i)+">"; text+=rs.getString(i); text+="</"+metaData.getColumnName(i)+">"; text+="n"; } text+="n"; }

System.out.println(text);

}

}

Listing 6

By:Ritika Wason 8

Page 9: A JDBC Tutorial

JDBC Database Connectivity

Figure 4

By:Ritika Wason 9