Java how to read database meta data in jdbc
JDBC (Java Database Connectivity) API provides a DatabaseMetaData
interface to obtain information about the database you are connected to. Using this interface, you can read the metadata information about the database, such as tables, columns, indexes, and procedures.
Here's an example code snippet that demonstrates how to read database metadata in JDBC:
import java.sql.*; public class DatabaseMetaDataExample { public static void main(String[] args) throws SQLException { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "mypassword"); DatabaseMetaData metaData = connection.getMetaData(); System.out.println("Database Name: " + metaData.getDatabaseProductName()); System.out.println("Database Version: " + metaData.getDatabaseProductVersion()); ResultSet tables = metaData.getTables(null, null, null, new String[] {"TABLE"}); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table Name: " + tableName); ResultSet columns = metaData.getColumns(null, null, tableName, null); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); System.out.println("\tColumn Name: " + columnName + " Column Type: " + columnType); } columns.close(); } tables.close(); connection.close(); } }Source:www.theitroad.com
This code connects to a MySQL database, retrieves the metadata for the database using the getMetaData()
method of the Connection
interface, and then uses various methods of the DatabaseMetaData
interface to print the metadata information to the console. In this example, we retrieve the database name and version, and then iterate through all the tables in the database and print their names along with the names and types of their columns.
Note that the specific metadata information available may vary depending on the database and the JDBC driver being used.