In Java, the PreparedStatement interface is a crucial interface primarily used for executing SQL statements with parameters to prevent SQL injection and improve the performance of database operations. The following are some commonly used PreparedStatement interface methods:
-
setString(int parameterIndex, String x) This method sets a string parameter into the precompiled SQL statement.
parameterIndexspecifies the parameter's index, andxis the string value to set. For example, to query user information for a specific username, you can write:javaPreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE username = ?"); pstmt.setString(1, "alice"); -
setInt(int parameterIndex, int x) This method sets an integer parameter into the precompiled SQL statement. For example, to query a user by their ID:
javaPreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE user_id = ?"); pstmt.setInt(1, 1001); -
executeQuery() This method executes SQL statements that return a result set (such as SELECT). It returns a
ResultSetobject, which can be used to read the query results.javaResultSet rs = pstmt.executeQuery(); while (rs.next()) { String username = rs.getString("username"); // Process each row } -
executeUpdate() This method executes SQL statements that do not return a result set (such as INSERT, UPDATE, DELETE). It returns an integer representing the number of affected rows.
javaint affectedRows = pstmt.executeUpdate(); System.out.println("Number of affected rows: " + affectedRows); -
setDouble(int parameterIndex, double x) This method sets a double-precision floating-point number into the precompiled SQL statement. For example, to update a product's price:
javaPreparedStatement pstmt = connection.prepareStatement("UPDATE products SET price = ? WHERE product_id = ?"); pstmt.setDouble(1, 19.99); pstmt.setInt(2, 202); -
clearParameters() This method clears all parameters previously set in the current
PreparedStatementobject. It is particularly useful when reusing the samePreparedStatementwith different parameters across multiple operations.javapstmt.clearParameters(); -
setDate(int parameterIndex, Date x) This method sets a
java.sql.Dateparameter for handling date data.javajava.sql.Date sqlDate = java.sql.Date.valueOf("2021-12-31"); pstmt.setDate(1, sqlDate); -
close() This method closes the
PreparedStatementobject and releases associated resources. It is essential to close thePreparedStatementafter completing database operations to avoid resource leaks.javapstmt.close();
These methods provide developers with powerful tools for database operations, effectively preventing SQL injection attacks, and compared to the standard Statement, PreparedStatement typically executes faster.