|
Developers Home > Products & Technologies > Java Technology > J2EE > JDBC > Learning > Tutorial and Code Camps > jGuru: JDBC 2.0 Fundamentals > |
|
|
| |
Tutorials
[About This Course| Exercises] Course Outlineo SQL o ODBC o The Java Programming Language and JDBC o JDBC 1.0 o JDBC 2.0 o Inserting Information into a Database o Retrieving Information from a Database · Connecting a Java Program to a Database o Areas Controlled by the Connection Interface o Generalizing Connection Information · Statements, ResultSets, and Interacting with a Database · JDBC Exception Types and Exception Handling · Metadata · Escape Syntax and Scalar Functions o Setup, Invocation, and Value Retrieval o Commit o Rollback o Handling BatchUpdateException § Typical BatchUpdateException Handler · LOBs o Locators o Clob o Blob · The JDBC 2.0 Optional Package and J2EE · Using JDBC with JavaServer Pages · Cloudscape Installation and Setup · Starting and Stopping Cloudscape o Books § Books Introduction to JDBCJDBC is a Java API (Application Programming Interface) that documents a standard framework for dealing with tabular and, generally, relational data. While JDBC 2.0 begins a move to make SQL semi-transparent to the programmer, SQL is still the lingua franca of the standard database engines and represents a major industry victory in the effort to separate data from code. Before getting into the course proper, it's worth taking a few moments to provide some background on the movement from straight-ahead SQL to JDBC. SQLSQL is a standardized language used to create, manipulate, examine, and manage relational databases. This course will not extensively explain SQL, although a very basic SQL Primer and SQL Resources are provided. However, you should understand the following: · A database is essentially a smart container for tables. · A table is a container comprised of rows. · A row is (conceptually) a container comprised of columns. · A column is a single data item having a name, type, and value. While you should review the definitions and understand the important differences, initially you can use the following analogs: A database approximates a file system; a table approximates a file; a row approximates a record or structure; and a column approximates a field or variable. If these terms are unfamiliar, you should review some programming resources, particularly in the area of Input/Output (I/O) operations, before proceeding with the course. Because SQL is an application-specific language, a single statement can be very expressive and can initiate high-level actions, such as sorting and merging, on an entire set of data. SQL was standardized in 1992 so that a program could communicate with most database systems without having to change the SQL commands. However, you must connect to a database before sending SQL commands, and each database vendor has a different interface to do so, as well as different extensions of SQL. Enter ODBC. ODBCODBC (Open Database Connectivity), a C-based interface to SQL-based database engines, provides a consistent interface for communicating with a database and for accessing database metadata (information about the database system vendor, how the data is stored, and so on). Individual vendors provide specific drivers or "bridges" to their particular database management system. Consequently, thanks to ODBC and SQL, you can connect to a database and manipulate it in a standard way. It is no surprise that, although ODBC began as a PC standard, it has become nearly an industry standard. Although SQL is well-suited for manipulating databases, it was not designed to be a general application language; rather, it was intended to be used only as a means of communicating with databases. Another more general and complete programming language is needed to host and feed SQL statements to a database and process results for data manipulation, visual display, or report generation. Unfortunately, you cannot easily write a program that will run on multiple platforms, even though the database connectivity standardization issue has been largely resolved. For example, if you wrote a database client in C++, you might have to totally rewrite the client for another platform; that is to say, your PC version would not run on a Macintosh. There are two reasons for this. First, C++ as a language is not portable because C++ is not completely specified (for example, how many bits does an The Java Programming Language and JDBCA Java program, written properly and according to specification, can run on any Java technology-enabled platform without recompilation. The Java programming language is completely specified and, by definition, a Java technology-enabled platform must support a known core of libraries. One such library is the Note: While portable applications and a standard database interface are major achievements, keep in mind that, for historical, competitive, and sometimes nonsensical reasons, the various databases are not completely standardized. This may mean that you have to aim for a lowest common denominator in terms of capabilities or build-in adjustments for specific databases, even on the same platform. This problem remains whether you use standard SQL, ODBC, JDBC, or other solutions. A JDBC driver is a class that implements the JDBC JDBC 1.0The JDBC 1.0 API provided the basic framework for data access, consisting primarily of the following interfaces and classes: · · · · · · · · · · As you will see in this course, you pass a JDBC 2.0The JDBC 2.0 API is broken into two parts: the core API, which this course discusses, and the JDBC 2.0 Optional Package. In general, the JDBC 2.0 core API adds a few more classes, but is primarily concerned with performance, class enhancements and functionality, and the new SQL3 (also known as SQL-99) datatypes. The new functionality in the core API includes scrollable result sets, batch updates, programmatic inserts, deletes, and updates, performance hints, character streams for streams of internationalized Unicode characters, full precision for At the time this course was prepared, the JDBC 3.0 draft was under review and planned to be included in the 1.4 release of the JDK. A Complete ExampleThe first hands-on experience with JDBC in this course involves a basic but complete example to illustrate the overall concepts related to creating and accessing information in a database. The fundamental issues encountered when writing any database application are: · Creating a database. A database can be created using tools supplied by the database vendor, or via SQL statements fed to the database from a Java program. Since there is normally a database administrator (of course, as a developer, this may be you), and not all JDBC drivers support database creation through Data Definition Language ( DDL), this topic will, in general, be left as DBMS (DataBase Management System) and driver specific. If you are interested in more details, there typically is a CREATE DATABASE statement, but be sure to review your DBMS SQL reference, as it is not part of the SQL standard, but is DBMS-dependent. · Connecting to the database. This is the first job of the JDBC driver, and specific information must be passed to it. The basic information requirements are a Database URL (Universal Resource Locator), a User ID, and a Password. Depending on the driver, there may be many other arguments, attributes, or properties available. Here are two examples: · Creating a table. While the database contains tables, the tables are the actual components that contain data, in the form of rows and columns. Table creation is accomplished by the DDL CREATE TABLE statement. This statement has many options, some differing from vendor to vendor; again, be sure to review your DBMS SQL reference for specifics. · Inserting information into a database. Again, data can be entered and maintained using database-specific tools, or with SQL statements sent programmatically. This course, as might be expected, will focus on using JDBC to send SQL statements to the database. · Selectively retrieving information. After sending SQL commands to retrieve the data and using JDBC to get results into variables, program code works as with any other variables to display or manipulate that data. Describing the ScenarioThe initial task for this example requires setting up the structures and inserting data to track java (that is, coffee) intake at the jGuru Jive Java Jumphouse, better known to the initiated as the 4J Cafe. Then a report must be generated for 4J Cafe management that includes total coffee sales and the maximum coffee consumed by a customer in one day. Here's the data: Coffee Consumption at the jGuru Jive Java Jumphouse
Creating a DatabaseAs noted aboolean autoCommitve, database creation is DBMS-specific. To aid in understanding the example, an exception is made here to the basic course rule of adherence to JDBC standards. A database is created in Cloudscape by setting a database connection URL attribute that is passed to the driver. As you will see shortly, this attribute is: Note: Keep in mind that this is Cloudscape's method and does not necessarily apply to any other DBMS. For example, to create the database on UDB2/NT, Connecting to the DatabaseThere are always two steps to making a database connection using the 1. Load the JDBC driver. You must load a driver that enables the JDBC classes to communicate with a data source. In the initial examples, the driver class used with Cloudscape, Class.forName( DriverClassName); A standard JDBC Compliant driver should also create a new instance of the driver class with this code. Unfortunately, in practice this does not work for all cases. For that reason, the exercises use the following code: Class.forName(DriverClassName).newInstance(); While this code will create an additional object in many cases, the code required to determine whether an instance was created, and to create a new instance if not, generally outweighs that extra cost. Fortunately, the garbage collector eventually cleans up the unreferenced object and the Drivers can also be specified from the command line via the java -Djdbc.drivers=DriverClassName AJavaApp The specific DriverClassName used in this course for connecting to Cloudscape in the recommended set up is: COM.cloudscape.core.RmiJdbcDriver 2. Connect to a data source. The driver supplies methods to make a One obvious point that is often taken for granted: the use of URLs means that JDBC applications are more or less automatically network and internet enabled. Given that this sample uses Cloudscape's driver, the URL required takes the following form: jdbc:cloudscape:rmi:jGuru;create=true Using the Connection con = DriverManager.getConnection( URL, Username, Password );
This form is best for portability even in cases where Username and Password are empty strings ( Creating a TableWhile the Statement stmt = con.createStatement(); At this point, the program can begin to do some actual work. To store the data, the example creates a table named
The code also indicates to the database that none of the columns may be NULL, mostly to avoid a sometimes troublesome area for SQL newcomers, and defines a primary key to identify each row. Inserting Information into a DatabaseNow that the table has been created, the data can be entered using the SQL INSERT statement: INSERT INTO JJJJData VALUES ( 1, 'John', 'Mon', 1, 'JustJoe' ) INSERT INTO JJJJData VALUES ( 2, 'JS', 'Mon', 1, 'Cappuccino' )INSERT INTO JJJJData VALUES ( 3, 'Marie', 'Mon', 2, 'CaffeMocha' ) ... In the example program, an array named "(1, 'John', 'Mon', 1, 'JustJoe')" The program code corresponding to the stmt.executeUpdate( "INSERT INTO JJJJData VALUES " + SQLData[i] );
Step by StepTo briefly review the discussion so far: First, any JDBC program loads a JDBC driver and creates a URL using the The exercise for this section includes the source code for a complete application to create the table Exercise1. Creating and Populating a Table Retrieving Information from a DatabaseTo retrieve information from a database, you send SQL Consider, for example, how to obtain the maximum number of cups of coffee consumed by a 4J Cafe customer in one day. In terms of SQL, one way to get the maximum value is to sort the table by the SELECT Entry, Customer, DOW, Cups, Type FROM JJJJData ORDER BY Cups DESC
In a program, execute the SQL statement with: ResultSet result = stmt.executeQuery( "SELECT Entry, Customer, DOW, Cups, Type " + "FROM JJJJData " + "ORDER BY Cups DESC");
Data Navigation
if( result.next() ) The if-statement collects the data. After that, a loop while(result.next()) is used, to allow the program to continue to the end of the data. Data ExtractionOnce positioned at a row, the application can get the data on a column-by-column basis using the appropriate
The program uses If all goes well, the output shows that: JS consumed the most coffee, 9 Espressos on Friday! The total cups of coffee consumed was 48. The row by row output is:
Note that the The exercise for this section includes the source code for a complete application to examine the ExerciseIn concluding this section, remember that: 1. JDBC is portable. The driver name and URL, user, and password data have been hard-coded here to keep things simple. By substituting variables for this information, these programs will run with any JDBC Compliant driver. 2. All of the code and material presented in this section applies to and runs under JDK 1.1 and JDBC 1.2 with the proper driver. From this point on, however, the course assumes that JDK 1.3 and JDBC 2.0 are available (but most of the material runs happily under JDK 1.2 as well). Connecting a Java Program to a DatabaseA Connection object represents and controls a connection to a database. While everything in JDBC depends on the capabilities of the database and the JDBC driver, in general, you can have multiple connections to the same database and/or connections to multiple databases. The DriverManager class handles driver registration and provides methods for obtaining a One of the first steps in obtaining a jdbc:cloudscape:rmi:jGuru which translates into jdbc: <subprotocol>: <subname> jdbc: cloudscape:rmi: jGuru This is fairly straightforward, primarily because the client and the server run on the same machine. Similar URLs are often seen with drivers below a type 4, because there is some other setup involved and the information required to locate a server is obtained from the setup information. Even here, things are not always as they seem. Most DBMS engines that support remote (and even local) connections do so using a TCP/IP (Transmission Control Protocol/Internet Protocol) port. Actually, even Cloudscape does with the When applications attempt to connect to a network or internet server, identification/location information must be provided. The general JDBC way is to use jdbc:cloudscape:rmi:jGuru;create=true The ;create=true portion is an attribute using Cloudscape syntax. The moral is: review the documentation for your driver and database. A
Areas Controlled by the Connection InterfaceMost of the preceding section relates to setup for · Creating · Obtaining · Controlling transactions via the · Setting the isolation level involved in transactions. There's even a method to obtain any SQL statement in a given database's native dialect, appropriately named Before moving on, the new DataSource class introduced in the JDBC 2.0 Optional Package should be mentioned. The specification recommends Generalizing Connection InformationIt should be evident from the above discussion of information needed to obtain a
Exercises3. Generalizing Connection Information - Batch 4. Generalizing Connection Information - Interactive Statements, ResultSets, and Interacting with a DatabaseA Statement object is a container or transport mechanism to send/execute (normally) SQL statements and retrieve any results via its associated Statement stmt = con.createStatement(); The execute series are the most often used of · executeQuery() is used to execute SQL statements that return a single ResultSet. · executeUpdate() is used to execute SQL statements that modify a table or values of columns in a table and return the number of rows affected (which is zero in the case of DDL statements). · execute() can be used to execute any type of SQL statement, but is intended for those that can return multiple results or values. execute() is not discussed further in the course. To allow the most flexibility to work with various databases and data sources, JDBC places no restriction on the kinds of SQL statements that a A Modifying DataUpdate has a specific meaning to programmers and, indeed, to SQL, so JDBC defines types to match SQL data types. These must be appropriate to the data to avoid technical problems, unanticipated results, and to promote job retention. See Java-SQL Type Equivalence for further information on the available and appropriate types.
ExerciseDatabase Queries
The default
Columns should be read from left to right (the same order as in the
A A Exercise6. Selecting Data and Presenting Information Prepared StatementsA · The contained SQL is sent to the database and compiled or prepared beforehand. From this point on, the prepared SQL is sent and this step is bypassed. The more dynamic · A · Note: The SQL3 types, in general, assume usage of prepared statements for DML. Here are two examples of setting up and obtaining prepared statements:
The question marks are stand-ins for values to be set before statement execution and are called parameter markers. These are referred to by number, starting from 1, in left to right order.
You can also prepare a statement that has no parameters. Note that ExerciseJava-SQL Type EquivalenceJDBC defines Common SQL Types--Standard Retrieval Methods
For display purposes, SQL3 Types--Retrieval Methods
This may seem very clear and basic, but the professional programmer should spend some time reading both Mapping SQL data types into Java and Mapping SQL and Java Types. In particular, review the table Conversions by ResultSet.getXXX() Methods to see the variety of options available. "How do I get the type into the database in the first place?" is a question frequently asked regarding the SQL3 types that use Locators, due to unfortunate gaps in the documentation. The best general answer to this is to look at the corresponding class (for example, JDBC Exception Types and Exception Handling"I don't want to think about it." That's probably an honest developer's response to queries regarding exception/error handling in general, which is difficult to do properly and usually unrewarding. It is also critical to production quality applications. The exercises in this course highlight specific JDBC areas and make no pretensions about being production quality. At the same time, a level of exception handling has been present, starting with the first exercise. However, that level has not been complete and it's time to remedy that with an introduction to the three types of Note that a fourth type, SQL ExceptionsMany of the methods in the · · |