Junior — Middle
How is the execution of a scheduled SQL query carried out?
sobes.tech AI
Answer from AI
In Java, executing a scheduled SQL query is usually done through JDBC (Java Database Connectivity). The main steps:
- Establish a connection to the database using
DriverManager.getConnection(). - Create a
PreparedStatementorStatementobject with the SQL query. - Execute the query using
executeQuery()for data retrieval orexecuteUpdate()for modifications. - Process the results through
ResultSet. - Close resources after execution.
Example:
String sql = "SELECT * FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, 10); // set parameter
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("User name: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}