Which class is used to establish a database connection in JDBC?

Which class is used to establish a database connection in JDBC? 

a) java.sql.Connection 
b) java.sql.DriverManager 
c) java.sql.Statement 
d) java.sql.ResultSet 

Answer:

b) java.sql.DriverManager 

Explanation:

The java.sql.DriverManager class is used to establish a database connection in JDBC. It provides methods for registering drivers and creating connections to a database. 

To establish a connection, you typically use the getConnection method of the DriverManager class. This method requires a database URL, which varies depending on your DBMS, and optionally a username and password if required by your database.

Here's an example of how you might use it:
        try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");

            // Step 2:Create a statement using connection object
            Statement statement = connection.createStatement();) {

            // Step 3: Execute the query or update query
            statement.execute(createTableSQL);
        } catch (SQLException e) {

            // print SQL exception information
            printSQLException(e);
        }
However, this assumes that the appropriate JDBC driver has been loaded, which is typically done with Class.forName("com.example.jdbc.Driver")

It's important to note that in more complex applications, connection pooling (e.g., Apache DBCP, C3P0) or a DataSource (e.g., as provided by a Java EE server) is often used instead of DriverManager for performance and scalability reasons.

Comments