Java - JDBC - DriverManager Class

The DriverManager class is a part of the Java JDBC API that manages the JDBC drivers that are used to connect to databases. It is responsible for loading the correct driver and providing a database connection to the application.

The DriverManager class has several important methods that allow developers to connect to a database:

  • registerDriver(Driver driver): This method registers a JDBC driver with the DriverManager. It is usually called by the driver's implementation class when it is loaded.
  • getConnection(String url, String username, String password): This method establishes a connection to the database using the specified URL, username, and password.
  • getConnection(String url, Properties info): This method establishes a connection to the database using the specified URL and properties.

The DriverManager class is typically used to establish a connection to a database as follows:

  • Load the JDBC driver using the Class.forName() method. This is required only for older JDBC drivers that do not support automatic driver loading.
  • Call the getConnection() method of the DriverManager class to establish a connection to the database.
  • Use the Connection object to create statements and execute SQL queries.
  • Close the connection when it is no longer needed using the close() method of the Connection object.
// Load the MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Set up the database connection properties
String url = "jdbc:mysql://localhost:3306/mydatabase";
Properties props = new Properties();
props.setProperty("user", "myusername");
props.setProperty("password", "mypassword");

// Establish a connection to the database
Connection conn = DriverManager.getConnection(url, props);

// Use the connection to execute SQL queries
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

// Close the connection and release resources
rs.close();
stmt.close();
conn.close();