JAVA SP T


Lets dive into snapshot of my programs!💻

8.Write a Java program to connect the Java API to Database, if connection not successful then throw an exception

💡Code:

 import java.sql.Connection;
              import java.sql.DriverManager;
              import java.sql.SQLException;
              
              public class DatabaseConnectionExample {
              
                  public static void main(String[] args) {
                      try {
                          Connection connection = connectToDatabase();
                          System.out.println("Connected to the database successfully!");
                          // Perform database operations here
              
                          // Don't forget to close the connection when done
                          connection.close();
                      } catch (SQLException e) {
                          System.err.println("Error: " + e.getMessage());
                          e.printStackTrace();
                      }
                  }
              
                  public static Connection connectToDatabase() throws SQLException {
                      String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
                      String username = "your_username";
                      String password = "your_password";
              
                      return DriverManager.getConnection(jdbcUrl, username, password);
                  }
              }
              

📸Output :

output