OneCompiler

ja13

122
  1. Write a Java program to display information about the database and list all the tables in
    the database. (Use DatabaseMetaData). [15 M]
    import java.sql.*;

public class DatabaseInfo {
public static void main(String[] args) {
try {
// Establish connection to the database
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");

        // Get DatabaseMetaData
        DatabaseMetaData metaData = connection.getMetaData();
        
        // Display information about the database
        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());
        
        // List all the tables in the database
        ResultSet tables = metaData.getTables(null, null, "%", null);
        System.out.println("\nTables in the database:");
        while (tables.next()) {
            System.out.println(tables.getString("TABLE_NAME"));
        }
        
        // Close connection
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

  1. Write a Java program to show lifecycle (creation, sleep, and dead) of a thread. Program
    should print randomly the name of thread and value of sleep time. The name of the
    thread should be hard coded through constructor. The sleep time of a thread will be a
    random integer in the range 0 to 4999.
    public class LifecycleThread extends Thread {
    private String threadName;

    public LifecycleThread(String name) {
    this.threadName = name;
    }

    @Override
    public void run() {
    System.out.println("Thread " + threadName + " is created.");

     // Sleep for a random interval between 0 and 4999 milliseconds
     int sleepTime = (int) (Math.random() * 5000);
     try {
         Thread.sleep(sleepTime);
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
     
     System.out.println("Thread " + threadName + " has slept for " + sleepTime + " milliseconds.");
     
     System.out.println("Thread " + threadName + " is dead.");
    

    }

    public static void main(String[] args) {
    LifecycleThread thread1 = new LifecycleThread("Thread1");
    LifecycleThread thread2 = new LifecycleThread("Thread2");

     // Start the threads
     thread1.start();
     thread2.start();
    

    }
    }