Get table information from DatabaseMetaData in Java
Description
The following code shows how to get table information from DatabaseMetaData.
Example
/*w w w. j a va 2 s . c o m*/
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
DatabaseMetaData mtdt = conn.getMetaData();
ResultSet rs = mtdt.getTables(conn.getCatalog(), "%", "%", null);
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
for (int i = 1; i <= numCols; i++) {
if (i > 1)
System.out.print(", ");
System.out.print(rsmd.getColumnLabel(i));
}
System.out.println("");
while (rs.next()) {
for (int i = 1; i <= numCols; i++) {
if (i > 1)
System.out.print(", ");
System.out.print(rs.getString(i));
}
System.out.println("");
}
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
The code above generates the following result.