The java.sql.Connection interface is a fundamental component of JDBC. It represents a connection between a Java program and a database.
The Connection interface provides methods to establish a connection with a specific database and manage it. It allows you to submit SQL statements and queries, and retrieve results. It also enables you to commit and roll back transactions, set transaction isolation levels, and manage connections, among other things.
Here’s an example of how to establish a connection using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Example {
public static void main(String[] args) {
Connection conn = null;
try {
// Register the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
String url = "jdbc:mysql://localhost/coffeeDB";
String user = "root";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
// Do something with the connection
// Close the connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
In this example, we first register the MySQL JDBC driver using ‘Class.forName()‘. Then, we create a connection to a local MySQL database using ‘DriverManager.getConnection()‘, passing the database URL, username, and password as parameters. We can then perform various operations on the database using this connection. Finally, we close the connection using ‘conn.close()‘.
In summary, the Connection interface in JDBC provides a way to connect to a database, manage the connection, and perform various operations on the database.