10. Write a Java program to access the metadata of an SQL database.

PHOTO EMBED

Thu Oct 31 2024 16:18:17 GMT+0000 (Coordinated Universal Time)

Saved by @varuntej #kotlin

java 
Copy code 
import java.sql.Connection; 
import java.sql.DatabaseMetaData; 
import java.sql.DriverManager; 
 
public class DatabaseMetadata { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      DatabaseMetaData dbMeta = con.getMetaData(); 
      System.out.println("Database Product Name: " + dbMeta.getDatabaseProductName()); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
Database Product Name: MySQL
[OR]
import java.sql.*;

public class App {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";
        Connection connection = null;

        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish connection to the database
            connection = DriverManager.getConnection(jdbcURL, username, password);

            // Retrieve and print database metadata
            DatabaseMetaData metaData = connection.getMetaData();
            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());
        } catch (Exception e) {
            // Handle exceptions
            e.printStackTrace();
        } finally {
            // Close the connection
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
content_copyCOPY