import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseMetadataExample {
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; // Replace with
your DB URL
private static final String USERNAME = "your_username"; // Replace with your DB username
private static final String PASSWORD = "your_password"; // Replace with your DB password
public static void main(String[] args) {
Connection connection = null;
try {
// Establishing the connection
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Connected to the database successfully.");
// Accessing database metadata
DatabaseMetaData metaData = connection.getMetaData();
// Retrieve and display basic information
System.out.println("Database Product Name: " +
metaData.getDatabaseProductName());
System.out.println("Database Product Version: " +
metaData.getDatabaseProductVersion());
System.out.println("Driver Name: " + metaData.getDriverName());
System.out.println("Driver Version: " + metaData.getDriverVersion());
System.out.println("SQL Syntax: " + metaData.getSQLKeywords());
// Get and display the tables
System.out.println("\nTables in the database:");
ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
String tableName = tables.getString("TABLE_NAME");
System.out.println("Table: " + tableName);
// Get and display columns for each table
ResultSet columns = metaData.getColumns(null, null, tableName, null);
System.out.println(" Columns in " + tableName + ":");
while (columns.next()) {
String columnName = columns.getString("COLUMN_NAME");
String columnType = columns.getString("TYPE_NAME");
int columnSize = columns.getInt("COLUMN_SIZE");
System.out.printf(" %s (%s, Size: %d)%n", columnName, columnType,
columnSize);
}
}
} catch (SQLException e) {
System.err.println("SQL Exception: " + e.getMessage());
} finally {
// Closing the connection
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
System.err.println("Failed to close the connection: " + e.getMessage());
}
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter