Java - JDBC - Connection interface
The Connection interface in Java represents a connection with a specific database. It provides methods to create statements, commit transactions, and retrieve metadata about the database.
Here are some of the methods provided by the Connection interface:
- createStatement(): This method creates a new Statement object that can be used to execute SQL queries.
- prepareStatement(String sql): This method creates a PreparedStatement object that can be used to execute parameterized SQL queries.
- commit(): This method commits the current transaction.
- rollback(): This method rolls back the current transaction.
- setAutoCommit(boolean autoCommit): This method sets the auto-commit mode for the connection.
- getMetaData(): This method returns a DatabaseMetaData object that contains metadata about the database.
Here's an example of how to create a Connection object in Java using the DriverManager class:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
System.out.println("Connected to database.");
} catch (SQLException e) {
System.out.println("SQL exception occurred: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class not found exception occurred: " + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
System.out.println("Connection closed.");
}
} catch (SQLException e) {
System.out.println("SQL exception occurred: " + e.getMessage());
}
}
}
}
This code uses the DriverManager.getConnection() method to establish a connection with the MySQL database. The connection string contains the database URL, username, and password. Once the connection is established, the Connection object is used to perform database operations. Finally, the Connection object is closed in a finally block to ensure that the resources are released properly.