Junior — Middle
How does Java interact with a database through JDBC?
sobes.tech AI
Answer from AI
Java interacts with databases through JDBC (Java Database Connectivity) — an API that allows executing SQL queries and managing results.
Main steps of interaction:
- Loading the database driver.
- Establishing a connection to the database via
DriverManager.getConnection(). - Creating a
StatementorPreparedStatementobject to execute SQL queries. - Executing queries using
executeQuery()(for SELECT) orexecuteUpdate()(for INSERT, UPDATE, DELETE). - Processing results through the
ResultSetobject. - Closing resources (ResultSet, Statement, Connection) to free memory.
Example:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("User: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Thus, JDBC provides a standardized way to work with various DBMS from Java applications.