Statement and PreparedStatement

1. Statement:

  • Statement is used for executing simple SQL queries without parameters.

  • Each time a statement is executed, the SQL query is parsed and optimized by the database server, which can result in performance overhead.

  • Vulnerable to SQL Injection attacks as values are directly inserted into the query string.

Advantages:

  • Suitable for static and non-repetitive queries.

  • Simpler and easier to use for straightforward queries.

Disadvantages:

  • Prone to SQL Injection attacks.

  • Potential performance issues due to parsing and optimizing the query repeatedly.

Example using Statement (Java):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class StatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "username";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
             Statement statement = connection.createStatement()) {

            String sqlQuery = "SELECT * FROM users";
            ResultSet resultSet = statement.executeQuery(sqlQuery);

            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("Name: " + name + ", Age: " + age);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. PreparedStatement:

  • PreparedStatement is used for executing parameterized SQL queries. It allows you to create queries with placeholders (?), which are later replaced with actual values.

  • PreparedStatements are precompiled, which means they can be cached by the database server, leading to better performance.

  • Offers protection against SQL Injection attacks as parameters are treated as data, not part of the query.

Advantages:

  • Protection against SQL Injection attacks.

  • Better performance due to query caching and reuse.

Disadvantages:

  • Slightly more complex syntax.

Example using PreparedStatement (Java):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class PreparedStatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "username";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sqlQuery = "SELECT * FROM users WHERE age > ?";
            int minAge = 18;

            try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
                preparedStatement.setInt(1, minAge);

                ResultSet resultSet = preparedStatement.executeQuery();

                while (resultSet.next()) {
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
                    System.out.println("Name: " + name + ", Age: " + age);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • StatementExample: Uses Statement to retrieve all data from the users table.

  • PreparedStatementExample: Uses PreparedStatement to retrieve data from the users table where age is greater than a specified value. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.

Last updated