Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.2 Basic JDBC Example
469
Listing 18.3 FruitTest.java (continued)
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[1];
String url = DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
showFruitTable(driver, url, username, password);
}
/** Get the table and print all the values. */
public static void showFruitTable(String driver,
String url,
String username,
String password) {
try {
// Load database driver if not already loaded.
Class.forName(driver);
// Establish network connection to database.
Connection connection =
DriverManager.getConnection(url, username, password);
// Look up info about the database as a whole.
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =
dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion + "\n");
System.out.println("Comparing Apples and Oranges\n" +
"============================");
Statement statement = connection.createStatement();
String query = "SELECT * FROM fruits";
// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
// Look up information about a particular table.
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
// Column index starts at 1 (a la SQL) not 0 (a la Java).
for(int i=1; i
System.out.print(resultsMetaData.getColumnName(i) +
" ");
}
System.out.println();
// Print results.
while(resultSet.next()) {
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved