Junior — Middle
Have you interacted directly with a database through SQL queries?
sobes.tech AI
Answer from AI
Yes, direct interaction with a database through SQL queries is a common practice when working with Java. This is usually implemented using JDBC (Java Database Connectivity), which allows executing SQL queries against a database.
Example of a simple query using JDBC:
String query = "SELECT * FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
// process data
}
} catch (SQLException e) {
e.printStackTrace();
}
This approach gives full control over queries and allows optimizing interaction with the database.