fork download
  1. import java.sql.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5.  
  6. String url = "jdbc:mysql://localhost:3306/student_db";
  7. String username = "root";
  8. String password = "root";
  9.  
  10. try {
  11. // Load JDBC Driver
  12. Class.forName("com.mysql.cj.jdbc.Driver");
  13. System.out.println("Loading JDBC Driver...");
  14. System.out.println("Driver loaded successfully!");
  15.  
  16. // Establish Connection
  17. System.out.println("\nConnecting to the database...");
  18. Connection con = DriverManager.getConnection(
  19. url, username, password
  20. );
  21.  
  22. System.out.println("Connecting to:");
  23. System.out.println(url);
  24. System.out.println("Connection established successfully!");
  25.  
  26. // Execute Query
  27. System.out.println("\nPerforming database operations...");
  28.  
  29. String query = "SELECT * FROM Students";
  30. Statement stmt = con.createStatement();
  31.  
  32. System.out.println("Executing Query: " + query + ";");
  33.  
  34. ResultSet rs = stmt.executeQuery(query);
  35.  
  36. System.out.println("+----+----------------+-------+");
  37. System.out.printf("| %-2s | %-14s | %-5s |%n",
  38. "ID", "Name", "Marks");
  39. System.out.println("+----+----------------+-------+");
  40.  
  41. while (rs.next()) {
  42. System.out.printf("| %-2d | %-14s | %-5.1f |%n",
  43. rs.getInt("ID"),
  44. rs.getString("Name"),
  45. rs.getDouble("Marks"));
  46. }
  47.  
  48. System.out.println("+----+----------------+-------+");
  49.  
  50. System.out.println(
  51. "Database query executed successfully."
  52. );
  53.  
  54. // Close Resources
  55. System.out.println("\nClosing database resources...");
  56.  
  57. rs.close();
  58. stmt.close();
  59. con.close();
  60.  
  61. System.out.println("Connection closed successfully!");
  62. }
  63. System.out.println("Driver not found: " + e.getMessage());
  64. }
  65. catch (SQLException e) {
  66. System.out.println("Connection Error: " + e.getMessage());
  67. }
  68. }
  69. }
Success #stdin #stdout 0.11s 57856KB
stdin
Standard input is empty
stdout
Driver not found: com.mysql.cj.jdbc.Driver