-
Load the database driver: First, load the database driver using the
Class.forName()method. For example, for MySQL, you can useClass.forName("com.mysql.jdbc.Driver"). -
Establish a connection: Use the
DriverManager.getConnection()method to establish a connection to the database. Provide the database URL, username, and password. For example:Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password"); -
Create a Statement object: Create a
Statementobject through the connection to execute SQL statements, such asStatement stmt = conn.createStatement(); -
Execute SQL statements: Use the
Statementobject to execute SQL statements, which can be queries or update commands. For example, for queries, useResultSet rs = stmt.executeQuery("SELECT * FROM table_name");, and for updates, useint count = stmt.executeUpdate("UPDATE table_name SET column_name = value WHERE condition"); -
Process results: For query operations, process the returned
ResultSetobject to read data. For update operations, handle the number of affected rows or other results. -
Close the connection: After completing the operation, close the
ResultSet,Statement, andConnectionobjects to release database resources. This is typically placed within afinallyblock to ensure execution regardless of exceptions. For example:
javaif (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close();