Junior — Middle
How can SQL queries be executed via JDBC in Java?
sobes.tech AI
Answer from AI
In Java, executing SQL queries via JDBC can be done in several ways:
- Statement — used for executing simple SQL queries without parameters.
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
- PreparedStatement — allows executing parameterized queries, which enhances security (protection against SQL injection) and performance when called repeatedly.
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 10);
ResultSet rs = pstmt.executeQuery();
- CallableStatement — used for calling stored procedures in the database.
CallableStatement cstmt = connection.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 10);
ResultSet rs = cstmt.executeQuery();
Each of these methods is suitable for different tasks depending on the complexity and security requirements of the queries.