JD BC Short Course
JD BC Short Course
● Error handling.
Entry Points:
Course Notes
Exercises
Copyright © 1996 MageLang Institute. All Rights Reserved.
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright © 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
by Magelang Institute
Overview
Course Notes
Java Database Programming
● Introduction to JDBC
● A Complete Example
❍ Creating a Database
■ exercises
❍ Getting Information from a Database
■ exercise
❍ Obtaining Result MetaData Type Information
■ exercises
● Connecting a Java program to a database
❍ exercises
● Talking to a Database
❍ Database Updates
❍ Database Queries
■ exercises
❍ Prepared Statements
■ exercise
● Metadata
❍ Information about a database
■ exercises
❍ Information about a table within a database
■ exercise
● Transactions
● Stored Procedures
SQL Primer
● Creating Tables
● Accessing Columns
● Storing Information
● Resources
Copyright © 1996 MageLang Institute. All Rights Reserved.
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright © 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
by Magelang Institute
[Table of Contents]
Introduction to JDBC
SQL is a language used to create, manipulate, examine, and manage
relational databases. 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 data. SQL was standardized in 1992
so that a program could communicate with most database systems
without having to change the SQL commands. Unfortunately, you must
connect to a database before sending SQL commands, and each database
vendor has a different interface, as well as different extensions of SQL.
Enter ODBC.
ODBC, 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.
Though SQL is well suited for manipulating databases, it is unsuitable as
a general application language and programmers use it primarily as a
means of communicating with databases--another language is needed to
feed SQL statements to a database and process results for 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 would have to totally rewrite the
client for each 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 for the simple reason that C++ is not completely specified,
for example, how many bits does an int hold? Second and more
importantly, support libraries such as network access and GUI libraries
are different on each platform. Enter Java.
You can run a Java program on any Java-enabled platform without even
recompiling that program. The Java language is completely specified and,
by definition, a Java-enabled platform must support a known core of
libraries. One such library is JDBC, which you can think of as a Java
version of ODBC, and is itself a growing standard. Database vendors are
already busy creating bridges from the JDBC API to their particular
systems. JavaSoft has also provided a bridge driver that translates JDBC
to ODBC, allowing you to communicate with legacy databases that have
no idea that Java exists. Using Java in conjunction with JDBC provides a
truly portable solution to writing database applications.
The JDBC-ODBC bridge driver is just one of four types of drivers available
to support JDBC connectivity. It comes packaged with the JDK 1.1 (and
eventually with 1.1 browsers), or as a separate package for use with 1.0
systems.
A Complete Example
Running through a simple, but complete, example will help you grasp the
overall concepts of JDBC. The fundamental issues encountered when
writing any database application are:
● Creating a database. You can either create the database outside
of Java, via tools supplied by the database vendor, or via SQL
statements fed to the database from a Java program.
● Connecting to an ODBC data source. An ODBC data source is a
database that is registered with the ODBC driver. In Java you can
use either the JDBC to ODBC bridge, or JDBC and a vendor-specific
bridge to connect to the datasource.
● Inserting information into a database. Again, you can either
enter data outside of Java, using database-specific tools, or with
SQL statements sent by a Java program.
● Selectively retrieving information. You use SQL commands from
Java to get results and then use Java to display or manipulate that
data.
Creating a Database
For this example, consider the scenario of tracking coffee usage at the
MageLang University Cafe. A weekly report must be generated for
University management that includes total coffee sales and the maximum
coffee consumed by a programmer in one day. Here is the data:
Coffee Consumption at Cafe Jolt, MageLang University
"Caffeinating the World, one programmer at a time"
Programmer Day # Cups
Gilbert Mon 1
Wally Mon 2
Edgar Tue 8
Wally Tue 2
Eugene Tue 3
Josephine Wed 2
Eugene Thu 3
Gilbert Thu 1
Clarence Fri 9
Edgar Fri 3
Josephine Fri 4
To create this database, you can feed SQL statements to an ODBC data
source via the JDBC-ODBC bridge. First, you will have to create an ODBC
data source. You have many choices—you could, for example, connect an
Oracle or Sybase database. For simplicity and to cover the largest single
audience, create a text file as an ODBC datasource to use for this
example. Call this ODBC data source CafeJolt.
To enter the data into the CafeJolt database, create a Java application
that follows these steps:
1. Load the JDBC-ODBC bridge. You must load a driver that tells the
JDBC classes how to talk to a data source. In this case, you will
need the class JdbcOdbcDriver:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
This can also be specified from the command line via the jdbc.drivers
system property:
"programmer","day","cups"
"Gilbert","Mon",1
"Wally","Mon",2
"Edgar","Tue",8
"Wally","Tue",2
"Eugene","Tue",3
"Josephine","Wed",2
"Eugene","Thu",3
"Gilbert","Thu",1
"Clarence","Fri",9
"Edgar","Fri",3
"Josephine","Fri",4
The ODBC-text driver will also create a file called schema.ini containing
metadata:
[JoltData]
ColNameHeader=True
CharacterSet=OEM
Format=CSVDelimited
Col1=programmer Char Width 32
Col2=day Char Width 3
Col3=cups Integer
exercises
1. Getting Started.
2. Using JDBCTest.
3. Connecting to an ODBC datasource without JDBCTest.
Consider how you would obtain the maximum number of cups of coffee
consumed by a programmer in one day. In terms of SQL, one way to get
the maximum value is to sort the table by the cups column in descending
order. The programmer column is selected, so the name attached to the
most coffee consumption can also be printed. Use the SQL statement:
result.next();
2. Extracting data from the columns of that row. Perform:
System.out.println("Programmer "+name+
" consumed the most coffee: "+cups+" cups.");
resulting in the following output:
result = stmt.executeQuery(
System.out.println("Total sales of
"+cups+" cups of coffee.");
The output should be:
1. Selecting.
You will occasionally need to obtain type information about the result of a
query. For example, the SQL statement:
int numbers = 0;
jdbc:odbc:data-source-name
The getConnection method returns a Connection to the specified source using
the JDBC-ODBC driver. For example, to connect to an ODBC source called
mage with a user name of parrt and a password of mojava, you would use:
See the Getting Started exercise for specific information about setting up
ODBC data sources on a PC.
Exercises
1. Getting Started.
2. Using JDBCTest.
3. Connecting to an ODBC datasource without JDBCTest.
Talking to a Database
Given a connection to a database, you can send SQL statements to
manipulate that database. Using the Connection.createStatement method,
obtain a Statement object and then execute method executeQuery or
executeUpdate. JDBC does not put any restrictions on the SQL you send via
the execute methods. but you must ensure that the data source you are
connecting to supports whatever SQL you are using. To be
JDBC-compliant, however, the data source must support at least SQL-2
Entry Level capabilities.
Database Updates
Assuming the variable con contains a valid Connection object obtained from
the method DriverManager.getConnection, simple SQL update statements
(SQL INSERT, UPDATE or DELETE) can be sent to your database by
creating a Statement and then calling method executeUpdate. For example,
to create a table called Data with one row of data, use the following:
Database Queries
In order to query a database (via the SQL SELECT statement), use the
method executeQuery, which returns a ResultSet object. The ResultSet object
returned is never null and contains the rows of data selected by the SQL
statement. For example, the following code fragment selects two columns
of data from our table called Data in ascending height order:
method ResultSet.next moves the cursor from row to row. Before reading
the first row, call method next to initialize the cursor to the first row. The
following code fragment shows how to read the first two rows of data and
print them out.
String name;
int height;
if ( result.next() ) { // move to first row
name = result.getString("name");
height = result.getInt("height");
System.out.println(name+":"+height);
}
if ( result.next() ) { // get second row
name = result.getString("name");
height = result.getInt("height");
System.out.println(name+":"+height);
}
The method next returns false when another row is not available.
Note that column names are not case-sensitive, and if more than one
column has the same name, the first one is accessed. Where possible,
the column index should be used. You can ask the ResultSet for the index
of a particular column if you do not know it beforehand.
exercises
1. Selecting.
2. Using MetaData.
Prepared Statements
prep.setString(1, "Jim");
prep.setInt(2, 70);
Finally, execute the the prepared statement with the parameters set
most recently via the executeUpdate method:
if (prep.executeUpdate () != 1) {
throw new Exception ("Bad Update");
}
exercise
1. Command-Line Guestbook.
Metadata
You can access information about the database as a whole, or about a
particular query ResultSet. This section describes how DatabaseMetaData and
ResultSetMetaData objects are obtained and queried.
if (md==null) {
System.out.println("No Database Meta Data");
} else {
System.out.println("Database Product Name : " +
md.getDatabaseProductName());
System.out.println("Allowable active connections: "+
md.getMaxConnections());
}
See the DatabaseMetaData API for more information.
Exercises
To find out the number and types of the columns in a table accessed via
a ResultSet, obtain a ResultSetMetaData object.
exercise
1. Using MetaData.
Transactions
A transaction is a set of statements that have been executed and
committed or rolled back. To commit a transaction, call the method
commit on the appropriate connection; use the rollback to remove all
changes since the last commit. By default, all new connections are in
auto-commit mode, which means that each "execute" is a complete
transaction. Call Connection.setAutoCommit to change the default. Any locks
held by a transaction are released upon the method commit.
Stored Procedures
A stored procedure is a block of SQL code stored in the database and
executed on the server. The CallableStatement interface allows you to
interact with them. Working with CallableStatement objects is very similar to
working with PreparedStatements. The procedures have parameters and can
return either ResultSets or an update count. Their parameters can be
either input or output parameters. Input parameters are set via the
setXXX methods. Output parameters need to be registered via the
CallableStatement.registerOutParamter method. Stored procedures need to be
supported by the database in order to use them. You can ask the
DatabaseMetaData if it supports it via the method supportsStoredProcedures.
AS
BEGIN
SELECT @dayTotal = sum (cups)
FROM JoltData
WHERE day = @day
END
The Java code is:
For example, given a ResultSet containing rows of names and dates, you
can use getString and getDate to extract the information:
SQLExceptions
SQLWarnings
Data Truncation
Exercise
SQL Conformance
Although SQL is a standard, not all JDBC drivers support the full ANSI92
grammar. Luckily, you can determine the level of conformance by asking.
The DatabaseMetaData object contains three methods that report the
grammar level supported by a driver.
● supportsANSI92EntryLevelSQL
All JDBC-compliant drivers must return true.
● supportsANSI92IntermediateSQL
In addition to multiple ANSI92 support levels for JDBC drivers, there are
multiple SQL support levels for ODBC sources. You can determine the
level of these too by asking. The DatabaseMetaData object contains three
methods that report the grammar level supported by a database.
● supportsMinimumSQLGrammar
● supportsCoreSQLGrammar
● supportsExtendedSQLGrammar
Exercise
Enterprise APIs
JDBC is just one part of what JavaSoft calls the Java Enterprise APIs. The
remaining three parts are Remote Method Invocation (RMI) for
Java-to-Java communications, via RPC-like calls, Java IDL for
Java-to-CORBA connectivity through OMG's Interface Definition Language
specification, and Java Naming and Directory Interface (JNDI) for
directory services support. Closely related is Java Object Serialization,
which permits programs to send objects across streams for persistence.
● RMI
● Serialization
● Java IDL
● JNDI
Resources
Some web-based resources:
● JDBC Guide
● JDBC Home
and books:
● Java Database Programming with JDBC by Prantik Patel and Karl
Moss (Coriolis Group ISBN 1-57610-056-1)
● Database Programming with JDBC and Java by George Reese
(O'Reilly ISBN 1-56592-270-0)
Copyright © 1996 MageLang Institute. All Rights Reserved.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright © 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
by Magelang Institute
[Table of Contents]
● R - Read
● U - Update
● D - Delete
Creating Tables
Use the CREATE TABLE statement when you want to create a table.
Because creating tables is such an important operation, it only
requires minimum conformance. However, some datasources, such
as Text ODBC sources, only support the simplest column elements,
with little or no constraint support.
NOT NULL |
UNIQUE |
PRIMARY KEY
Example:
Use the DROP TABLE statement when you want to drop a table. Like
CREATE TABLE, it only requires minimum conformance.
Accessing Columns
Use the SELECT statement when you want to retrieve a set of
columns. The set may be from one or more tables, and you can
specify the criteria to determine which rows to retrieve. Most of the
available clauses are available with minimum conformance.
Additional capabilities are available with the core grammar.
Storing Information
Use the INSERT statement when you want to insert rows. It too can
provide different capabilities depending upon the conformance level
supported.
Resources
Some web-based resources:
● Access FAQ
● dbANYWHERE FAQ
● Oracle FAQ
● Sybase FAQ
● Tina London's Guide to SQL
and books:
● Teach Yourself SQL in 14 Days by Bryan Morgan and Jeff
Perkins (Sams Publishing ISBN 0-67230-855-X)
● Understanding the New SQL: A Complete Guide by Jim Melton
and Alan Simon (Morgan Kaufman ISBN 1-55860-245-3)
● LAN Times Guide to SQL by James R. Groff & Paul N. Weinberg
(McGraw-Hill ISBN 0-07882-026-X)
Copyright © 1996 MageLang Institute. All Rights Reserved.
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright © 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.