Java Reference
In-Depth Information
and a table name, however, the program lists the name and data type of each col-
umn in that table.
An interesting feature of this GetDBInfo program is how it obtains the parameters
needed to connect to the database. The example operates on the premise that at
any given site, it is typically used to connect to the same database server, using the
same database driver, and may also be used with the same database username and
password. So, instead of requiring the user to type all this cumbersome informa-
tion on the command line each time the program is run, the program reads default
values from a file named DB.pr ops that is stored in the same directory as the Get-
DBInfo.class file. In order to run Example 17-2, you have to create an appropriate
DB.pr ops file for your system. On my system, this file contains:
# The name of the JDBC driver class
driver=org.gjt.mm.mysql.Driver
# The URL that specifies the database server.
# It should not include the name of the database to connect to
server=jdbc:mysql://db.domain.com/
# The database account name
user=david
# The password for the specified account. Not specified here
# Uncomment the line below to specify a password
#password=
Lines that begin with # are comments, obviously. The name = value format is the
standard file format for the java.util.Properties object that is used to read the
contents of this file.
After the program reads the default values from the DB.pr ops file, it parses its com-
mand-line arguments, which can override the driver , server , user , and password
properties specified in the file. The name of the database to connect to must be
specified on the command line; the database name is simply appended to the
server URL. The name of a table in the database can optionally be specified on the
command line. For example, you might run the program as follows:
% java com.davidflanagan.examples.sql.GetDBInfo api class
DBMS: MySQL 3.22.32
JDBC Driver: Mark Matthews' MySQL Driver 2.0a
Database: jdbc:mysql://localhost/api
User: david
Columns of class:
id : int
packageId : int
name : varchar
Example 17−2: GetDBInfo.java
package com.davidflanagan.examples.sql;
import java.sql.*;
import java.util.Properties;
/**
* This class uses the DatabaseMetaData class to obtain information about
* the database, the JDBC driver, and the tables in the database, or about
* the columns of a named table.
**/
public class GetDBInfo {
Search WWH ::




Custom Search