Enter your email address:

    Delivered by FeedBurner

JDBC Programming


JDBC is a programming interface that communicates your SQL commands to a database, retrieves the results, analyzes the results in whatever way you want them analyzed, displays the results retrieved from a database, and so on. This section shows two JDBC programs. The goal of the first program is to make the reader familiar with some of the more basic classes of the java.sql package. This we do by constructing a couple of database tables and then querying them, just as we did in our first command-line SQL session in the previous section. The goal of the second JDBC program is to show how information can be rapidly loaded into a database table from a file.

As we will show in our first example, all communication with a database is through the executeQuery method of Statement, a class in the java.sql package. A Statement object is constructed by invoking the createStatement method on an object of type Connection, which represents the communication link with the database. But, as mentioned earlier, at the very beginning one must first register an appropriate driver with the driver manager. Since we will be using a MySQL database, we would need to register the mm.mysql.Driver driver with the JDBC DriverManager by
Class.forName( "org.gjt.mm.mysql.Driver").newInstance();
This invocation results in an automatic registration of the driver with the JDBC DriverManager.
When a JDBC program queries a table with SELECT, the object returned is of type ResultSet, another class defined in java.sql. To display the information in a ResultSet retrieval, one must first figure out its structure, meaning the number of rows and columns in the retrieved object. All such structural information regarding a ResultSet object resides in the corresponding ResultMetaData object. For example, if rs is a ResultSet object, to figure out the number of columns in this object, we can say
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
One often does not need to know explicitly the number of rows in a ResultSet object. The operator next, when invoked on a ResultSet object, takes the flow of control automatically to the next row. Therefore, once we have figured out the number of columns in the ResultSet object rs as above, we can set up the following print loop to display all the contents of the ResultSet:
while ( rs.next() ) {
for ( int i = 1; i <= numCols; i++ ) { if ( i > 1 ) System.out.print( " | " );
System.out.print( rs.getString( i ) );
}
System.out.println( "" );
}
Here is the source code for the first example:
//DBFriends1.java
import java.sql.*;
class DBFriends1 {
public static void main( String[] args )
{
try {
Class.forName( "org.gjt.mm.mysql.Driver").newInstance();
String url = "jdbc:mysql:///test";
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
stmt.executeQuery( "SET AUTOCOMMIT=1" );
stmt.executeQuery( "DROP TABLE IF EXISTS Friends" );
stmt.executeQuery( "DROP TABLE IF EXISTS Rovers" );
// new table (Friends):
stmt.executeQuery("CREATE TABLE Friends(Name CHAR (30) PRIMARY KEY, +
"Phone INT, Email CHAR(30))" );
stmt.executeQuery(
"INSERT INTO Friends VALUES ( 'Ziggy Zaphod',
4569876," + "'ziggy@sirius' )" );
stmt.executeQuery("INSERT INTO Friends VALUES ( 'Yo Yo Ma', 3472828, " +
"yoyo@yippy' )" );
stmt.executeQuery("INSERT INTO Friends VALUES ( 'Gogo Gaga',
27278927," + " 'gogo'@garish')" );
//new table (Rovers):
stmt.executeQuery("CREATE TABLE Rovers ( Name CHAR (30) NOT NULL, " +
"RovingTime CHAR(10))" );
stmt.executeQuery("INSERT INTO Rovers VALUES ( 'Dusty Dodo','2 pm' )"));
stmt.executeQuery("INSERT INTO Rovers VALUES ( 'Yo Yo Ma', '8 pm' )" );
stmt.executeQuery("INSERT INTO Rovers VALUES ( 'BeBe Beaut', '6 pm')" );
// Query: which Friends are Rovers ?
ResultSet rs = stmt.executeQuery(SELECT Friends.Name, Rovers.RovingTime FROM Friends, "+ "Rovers WHERE Friends.Name = Rovers.Name" );
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
while (rs.next() ) {for (int i = 1; i <= numCols; i++) { if (i > 1) System.out.print(" | ");
System.out.print(rs.getString(i));
}
System.out.println("");
}
rs.close();
con.close();
} catch(Exception ex) {System.out.println(ex);}
}
}
To compile this program, you'd need to tell javac how to locate the database driver. If the driver is in a JAR file named mm.mysql-2.0.7-bin.jar, an invocation like the following should work
javac -classpath .:∼/mm.mysql-2.0.7-bin.jar DBFriends1.java
You'd also need to specify the classpath for the java application launcher :
java -classpath .:∼/mm.mysql-2.0.7-bin.jar DBFriends1

Read More

The MySql Database Manager


The MySQL database management system consists primarily of a MySQL server that can be accessed by a MySQL client for creating and using databases. MySQL also comes with a "terminal monitor"interactive program mysqlthat can be used for executing command-line SQL statements. This program can also be used to run SQL statements in a batch mode in which you place multiple statements in a file and then tell mysql to execute the contents of the file.


The rest of this section introduces some of the basic terminology of communicating with a database, our interest being specifically in communicating with MySQL databases. We will define and provide examples for the terms Driver Manager, bridge driver, and database URL.We will use Java-related examples for the terms, but the terms have the same meanings when C++ classes from Mysql++ are used for accessing a database.
As mentioned already, one communicates with a database through a database driver. It is the driver's job to figure out how to reach into the row—column representations of the tables of the database and to retrieve or modify the information at prescribed locations. There are a number of drivers available for communicating with a MySQL database. A commonly used driver by Java programs is the opensourceMM. MySQL driver.[4] In the same vein, other database systems have their own drivers. Many of these database systems, such as Access, dBase, DB2, Excel, Text, and so on, can be accessed with the ODBC (for Open DataBase Connectivity) driver that also understands SQL. While each of these database systems would have its own driver module, an ODBC driver would know how to "talk" to the product-specific drivers. A Java database program can communicate with all ODBC-accessible databases by using the JDBC-ODBC bridge driver.
Platforms that support database programming also usually provide a driver manager that knows about the various types of drivers commonly used today. For example, the DriverManagerclass in Java.sql will load in all the drivers referenced in the "jdbc.drivers" system property that can be included in a file of pathname .hotJava/properties at the top level of your home directory. One also has the option of loading into a JDBC program a specific driver by an invocation such as the following which works for the MM.
MySQL driver:
Class.forName( "org.gjt.mm.mysql.Driver").newInstance();
where the static method Class.forNamereturns the Class object associated with the class of name
org.gjt.mm.mysql.Driver.
A driver manager can also help establish a connection with a database. Using the example the JDBC
class DriverManager again, its method getConnectionreturns an object of type Connection
defined in the Java.sql package. The argument to the getConnection method is a specially formatted string that for MySQL is the name of the database. For example, if we want a Java program to make a connection with the MySQL database test that comes with MySQL installation, we'd need to make the calls
String url = "jdbc:mysql:///test";
Connection con = DriverManager.getConnection( url );
The string "jdbc:mysql:///test" is called a database URL (as opposed to the internet URL). If, on the other hand, we wanted a Java program to talk to an ODBC database, we could say
String url ="jdbc:odbc:myDatabaseName";
Connection con = DriverManager.getConnection( url );
If you are trying to reach a remote database over the internet, the database URL string may have to include the port number and other information, besides, of course, the internet address of the machine hosting the database.
If you have installed MySQL with default options on a personal Linux machine and you are just now becoming familiar with it, for the kinds of practice programs we will be discussing in this chapter you can start up the server daemon as root by invoking
safe_mysqld -Sg &
where safe_mysqld is a wrapper around the daemon executable mysqld that automatically invokes the proper options to use—unless they are overridden by command line options. The command line option Sg—which stands for "skip grant tables"—starts up the server without grant tables, giving all users full access to all tables. With default installation on a Linux machine, the database tables would ordinarily be stored in the directory /var/lib/mysql. The command
mysqld --help
shows all the options with which the daemon server program can be run. The following command when entered as root shuts down the server on a Linux machine
mysqladmin -u root shutdown
With default options, the server daemon will ordinarily monitor port 3306 for incoming connections.

Read More

Relational Databases


Consider, for example, a database for storing information on all the books in a library. Let's say that we want to store the following information on each book :
Title
Author
Year
ISBN
NumberOfCopies
Publisher
PublisherLocation
PublisherURL
PublisherRep
PublisherRepPhone
PublisherRepEmail


Let's assume that the library has 100,000 books that are published by, say, 100 publishers. For the sake of making a point, let's also assume that each publisher is represented equally well in the library. If we represented all the books in a single "flat" table with eleven columns, one for each of the items listed above, the information in at least three of the columns—those under the column headings "Publisher," "PublisherLocation," and "PublisherURL"—would be the same for the 1000 rows corresponding to each publisher. That obviously is not an efficient way to store the information. There would be too much "redundancy" in the table. Since it goes without saying that the larger the number of entries that need to made to create a table, the greater the probability of an error creeping into one or more of the entries, our table would be at an increased risk of containing erroneous information. The table with the column headings as shown above will also have redundancies with regard to the PublisherRep information.

Now consider an alternate design consisting of three tables, one containing information generic to each book, the other containing information generic to each publisher, and the third containing information generic to each publisher rep:

BookTable:
Title Author Year ISBN PublisherID PublisherRepID
PublisherTable:

PublisherID PublisherName PublisherLocation PublisherURL

where we have assumed that the PublisherRep might be specific to each book and that the same rep may represent multiple publishers. We now associate unique identifiers, possibly numerical in nature, in the form of PublisherIDand PublisherRepID to "link" the main book table, BookTable,with the other two tables, PublisherTableand PublisherRepTable. PublisherRepTable: PublisherRepID RepName RepPhone RepEmail

These three tables together would constitute a typical modern relationaldatabase. Given this database, we may now query the database for information that for simple queries can be extracted from a single table, but that for more complex queries may require simultaneous access to multiple tables. Here are examples of simple queries that can be fulfilled from just a single table:
Retrieve all book titles published in a given year.
Retrieve all book titles published by a given author.
Retrieve all publishers located in France.
Retrieve all publisher rep names.
etc.
and here are examples of queries that require simultaneous access to more than one table in the
database:
Retrieve all book titles along with the name of
the publisher for each book.
Retrieve all books for which the designated
publisher rep is given.
Retrieve all book titles published last year along
with the name of the publisher for each
and the name of the publisher's rep.
etc.
Other possible interactions with the database could consist of updating the database as the library acquires additional books, modifying the entries, and so on. Over the years, a command language called SQL for Structured Query Language(SQL) has come into widespread use for communicating with databases, especially the server-based databases.[1]Since JDBC and Mysql++ programs serve as interfaces to SQL, it is important to get a sense of the syntax of SQL
before launching into the syntax of JDBC and Mysql++. JDBC and Mysql++ programs send SQL queries to a database, analyze the results returned by the database, and display these results in forms desired by the user.

Read More

Qidzama

Recent Articles

Blog Archive