Java Reference
In-Depth Information
connect to the database. For example, you might invoke the
ExecuteSQL
program
and enter a simple query like this (note that this long Java command line has been
broken in two here):
% java com.davidflanagan.examples.sql.ExecuteSQL -d org.gjt.mm.mysql.Driver \
-u java -p nut jdbc:mysql://db.domain.com/api
sql> SELECT * FROM package WHERE name LIKE '%.rmi%'
+----+--------------------------------+
| id | name |
+----+--------------------------------+
| 14 | java.rmi |
| 15 | java.rmi.dgc |
| 16 | java.rmi.registry |
| 17 | java.rmi.server |
+----+--------------------------------+
sql> quit
Notice that
ExecuteSQL
uses the
execute()
method of its
Statement
object to exe-
cute SQL statements. Since the user can enter any kind of SQL statement, you have
to use this general-purpose method. If
execute()
returns
true
, the SQL statement
was a query, so the program retrieves the
ResultSet
and displays the results of
the query. Otherwise, the statement was an update, so the program simply outputs
information about how many rows in the database were affected by the update.
The
printResultsTable()
method handles displaying the results of a query. This
method gets a
ResultSetMetaData
object to find out some information about the
data returned by the query, so it can format the results appropriately.
There are two other important JDBC programming techniques to note in Example
17-1. The first is the handling of
SQLException
exceptions that are thrown. The
SQLException
object supports the standard exception message with
getMessage()
,
but it may also contain an additional message sent by the database server. You
obtain this message by calling the
getSQLState()
method of the exception object.
The second technique is the handling of warnings. The
SQLWarning
class is a sub-
class of
SQLException
, but warnings, unlike exceptions, are not thrown. When a
SQL command is executed, any warnings reported by the server are stored in a
linked list of
SQLWarning
objects. You obtain the first
SQLWarning
object in this list
by calling the
getWarnings()
method of the
Connection
object. If there are any
additional
SQLWarning
objects, you get the next one by calling the
getNextWarn-
ing()
method of the current
SQLWarning
object. In Example 17-1, these warnings
are displayed using a
finally
clause, so that they appear both when an exception
is thrown and when execution completes normally.
Example 17−1: ExecuteSQL.java
package com.davidflanagan.examples.sql;
import java.sql.*;
import java.io.*;
/**
* A general-purpose SQL interpreter program.
**/
public class ExecuteSQL {
public static void main(String[] args) {
Connection conn = null; // Our JDBC connection to the database server