Explain JDBC statements

Explain JDBC statements

In JDBC (Java Database Connectivity), statements are used to execute SQL queries against the database. There are three main types of JDBC statements:

1. Statement

 Used for executing static SQL queries. Suitable for executing simple SQL queries without parameters.

2. PreparedStatement

Used for executing precompiled SQL queries with or without input parameters. Provides better performance and security by preventing SQL injection attacks.

3. CallableStatement

Used for executing stored procedures in the database. Allows execution of complex database operations through stored procedures.

JDBC statements

Example

Let’s illustrate each type of JDBC statement with a complete example where we connect to a MySQL database, execute different types of queries, and process the results.

Database Table Creation
Before running the Java code, create a table in your database.
sql
CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    price DOUBLE
);

CREATE PROCEDURE getProductCount()
BEGIN
    SELECT COUNT(*) AS count FROM products;
END;


Java Program Using JDBC Statements
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCStatementsExample {
    public static void main(String[] args) {
        // JDBC URL, username, and password of MySQL server
        String jdbcURL = "jdbc:mysql://localhost:3306/your_database";
        String username = "root";
        String password = "password";

        // JDBC variables for opening and managing connection
        Connection connection = null;

        try {
            // Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish a connection
            connection = DriverManager.getConnection(jdbcURL, username, password);
            System.out.println("Connected to the database!");

            // 1. Using Statement to execute a static SQL query
            Statement statement = connection.createStatement();
            String insertSQL = "INSERT INTO products (name, price) VALUES ('Product1', 100.0)";
            statement.executeUpdate(insertSQL);
            System.out.println("Inserted a product using Statement");

            // 2. Using PreparedStatement to execute a precompiled SQL query with parameters
            String selectSQL = "SELECT * FROM products WHERE price > ?";
            PreparedStatement preparedStatement = connection.prepareStatement(selectSQL);
            preparedStatement.setDouble(1, 50.0);
            ResultSet resultSet = preparedStatement.executeQuery();

            System.out.println("Products with price greater than 50.0:");
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                double price = resultSet.getDouble("price");

                System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);
            }
            resultSet.close();
            preparedStatement.close();

            // 3. Using CallableStatement to execute a stored procedure
            CallableStatement callableStatement = connection.prepareCall("{CALL getProductCount()}");
            ResultSet rs = callableStatement.executeQuery();

            if (rs.next()) {
                int count = rs.getInt("count");
                System.out.println("Total number of products: " + count);
            }
            rs.close();
            callableStatement.close();

            // Close the resources
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                    System.out.println("Disconnected from the database.");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Explanation of the JDBC statements

1. Using Statement

  • Statement statement = connection.createStatement(); creates a Statement object.
  • statement.executeUpdate(insertSQL); executes a static SQL query to insert a product into the products table.

2. Using PreparedStatement

  • PreparedStatement preparedStatement = connection.prepareStatement(selectSQL); creates a PreparedStatement object for a SQL query with a parameter.
  • preparedStatement.setDouble(1, 50.0); sets the parameter value for the SQL query.
  • ResultSet resultSet = preparedStatement.executeQuery(); executes the query and returns a ResultSet object containing the results.

3. Using CallableStatement

  • CallableStatement callableStatement = connection.prepareCall(“{CALL getProductCount()}”); creates a CallableStatement object for executing a stored procedure.
  • ResultSet rs = callableStatement.executeQuery(); executes the stored procedure and returns a ResultSet object containing the results.

Homepage

Readmore