Which method is used to establish a connection to a database?

Java MCQ: Which method is used to establish a connection to a database?

a) DriverManager.connect()
b) DriverManager.getConnection()
c) Connection.create()
d) Database.connect()

Answer:

b) DriverManager.getConnection()

Explanation:

The DriverManager.getConnection() method is used to establish a connection to a database in JDBC. This method takes a database URL, a username, and a password as arguments and returns a Connection object that represents the established connection to the database.

Here’s an example of using DriverManager.getConnection():

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

This example connects to a MySQL database running on localhost with the database name mydb, using the specified username and password.

The getConnection() method is a fundamental part of JDBC for establishing connections to databases.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top