Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.3 Some JDBC Utilities
475
Listing 18.6 DatabaseUtilities.java (continued)
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
return(getQueryResults(connection, query, close));
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
return(null);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
return(null);
}
}
/** Retrieves results as in previous method but uses
* an existing connection instead of opening a new one.
*/
public static DBResults getQueryResults(Connection connection,
String query,
boolean close) {
try {
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
String[] columnNames = new String[columnCount];
// Column index starts at 1 (a la SQL) not 0 (a la Java).
for(int i=1; i
columnNames[i 1] =
resultsMetaData.getColumnName(i).trim();
}
DBResults dbResults =
new DBResults(connection, productName, productVersion,
columnCount, columnNames);
while(resultSet.next()) {
String[] row = new String[columnCount];
// Again, ResultSet index starts at 1, not 0.
for(int i=1; i
String entry = resultSet.getString(i);
if (entry != null) {
entry = entry.trim();
}
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