Java Reference
In-Depth Information
12
public static void main(String args[])
13
{
14
final String DATABASE_URL = "jdbc:derby:books" ;
final String SELECT_QUERY =
"SELECT authorID, firstName, lastName FROM authors" ;
15
16
17
18
// use try-with-resources to connect to and query the database
try (
Connection connection = DriverManager.getConnection(
DATABASE_URL , "deitel" , "deitel" );
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery( SELECT_QUERY ))
19
20
21
22
23
24
{
25
// get ResultSet's meta data
26
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
27
28
29
System.out.printf( "Authors Table of Books Database:%n%n" );
30
31
// display the names of the columns in the ResultSet
32
for ( int i = 1 ; i <= numberOfColumns; i++)
33
System.out.printf( "%-8s\t" ,
metaData.getColumnName(i)
);
34
System.out.println();
35
36
// display query results
37
while (resultSet.next())
38
{
39
for ( int i = 1 ; i <= numberOfColumns; i++)
40
System.out.printf( "%-8s\t" ,
resultSet.getObject(i)
);
41
System.out.println();
42
}
43
} // AutoCloseable objects' close methods are called now
44
catch (SQLException sqlException)
45
{
46
sqlException.printStackTrace();
47
}
48
}
49
} // end class DisplayAuthors
Authors Table of Books Database:
AUTHORID FIRSTNAME LASTNAME
1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
4 Dan Quirk
5 Michael Morgano
Fig. 24.23 | Displaying the contents of the Authors table. (Part 2 of 2.)
JDBC supports automatic driver discovery —it loads the database driver into memory
for you. To ensure that the program can locate the driver class, you must include the class's
location in the program's classpath when you execute the program. You did this for Java DB
in Section 24.5 when you executed the setEmbeddedCP.bat or setEmbeddedCP file on your
 
Search WWH ::




Custom Search