Java Reference
In-Depth Information
32.7.2 Obtaining Database Tables
You can identify the tables in the database through database metadata using the
getTables
method. Listing 32.6 displays all the user tables in the javabook database on a local MySQL
database. FigureĀ 32.25 shows a sample output of the program.
L
ISTING
32.6
FindUserTables.java
1
import
java.sql.*;
2
3
public class
FindUserTables {
4
public static void
main(String[] args)
5
throws
SQLException, ClassNotFoundException {
6
// Load the JDBC driver
7 Class.forName(
"com.mysql.jdbc.Driver"
);
8 System.out.println(
"Driver loaded"
);
9
10
// Connect to a database
11 Connection connection = DriverManager.getConnection
12 (
"jdbc:mysql://localhost/javabook"
,
"scott"
,
"tiger"
);
13 System.out.println(
"Database connected"
);
14
15
load driver
connect database
database metadata
DatabaseMetaData dbMetaData = connection.getMetaData();
16
17 ResultSet rsTables = dbMetaData.getTables(
null
,
null
,
null
,
18
new
String[] {
"TABLE"
});
19 System.out.print(
"User tables: "
);
20
while
(rsTables.next())
21 System.out.print(rsTables.getString(
"TABLE_NAME"
) +
" "
);
22
23
// Close the connection
24 connection.close();
25 }
26 }
obtain tables
get table names
F
IGURE
32.25
You can find all the tables in the database.
Line 17 obtains table information in a result set using the
getTables
method. One of the
columns in the result set is TABLE_NAME. Line 21 retrieves the table name from this result
set column.
32.7.3 Result Set Metadata
The
ResultSetMetaData
interface describes information pertaining to the result set. A
ResultSetMetaData
object can be used to find the types and properties of the columns in a
ResultSet
. To obtain an instance of
ResultSetMetaData
, use the
getMetaData
method
on a result set like this.
ResultSetMetaData rsMetaData = resultSet.getMetaData();
Search WWH ::
Custom Search