Describe the main steps of interacting with a database using JDBC.
sobes.tech AI
Answer from AI
-
Loading the driver: Use
Class.forName("com.mysql.cj.jdbc.Driver");or obtain aConnectionviaDriverManager(JRE 6+). -
Establishing the connection: Call
DriverManager.getConnection(url, user, password);. This returns aConnectionobject representing the session with the database. -
Creating a statement: Create a
Statementobject (for simple queries),PreparedStatement(for parameterized queries), orCallableStatement(for calling stored procedures) from theConnectionobject.// Creating a PreparedStatement PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?"); stmt.setInt(1, userId); -
Executing the query: Call the appropriate method on the statement object (
executeQueryfor SELECT,executeUpdatefor INSERT, UPDATE, DELETE).// Executing the query and getting the result ResultSet rs = stmt.executeQuery(); -
Processing the result: Iterate over the
ResultSetobject (if it was a SELECT query) usingnext()and retrieve data usinggetXXX()methods (e.g.,getString(),getInt()).// Processing results while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); // Further data processing } -
Closing resources: Close the
ResultSet,Statement, andConnectionobjects in the reverse order of their creation to free resources. Usually, atry-with-resourcesblock is used.// Closing resources using try-with-resources try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement stmt = conn.prepareStatement("..."); ResultSet rs = stmt.executeQuery()) { // Processing data while (rs.next()) { // ... } } catch (SQLException e) { // Handling exceptions e.printStackTrace(); }