Inserting Data using JDBC

Using Statement:

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

Steps to Execute an INSERT Query Using Statement:

  1. Establish a Connection: Establish a connection to the database.

  2. Create a Statement: Create a Statement object using the connection.

  3. Execute Query: Execute the SQL INSERT query using the Statement.

Example Code using Statement (Java):

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

public class StatementInsertExample {
    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 = "INSERT INTO users (name, age) VALUES ('John', 30)";
            int rowsAffected = statement.executeUpdate(sqlQuery);

            if (rowsAffected > 0) {
                System.out.println("Data inserted successfully!");
            } else {
                System.out.println("Failed to insert data.");
            }

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

Using PreparedStatement:

  • PreparedStatement is used for executing parameterized SQL queries.

Steps to Execute an INSERT Query Using PreparedStatement:

  1. Establish a Connection: Establish a connection to the database.

  2. Create a PreparedStatement: Create a PreparedStatement object with the parameterized query using the connection.

  3. Set Parameters: Set the parameter values using setter methods of the PreparedStatement.

  4. Execute Query: Execute the PreparedStatement.

Example Code using PreparedStatement (Java):

Explanation:

  • StatementInsertExample: Uses Statement to insert data directly into the users table.

  • PreparedStatementInsertExample: Uses PreparedStatement to insert data into the users table. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.

Last updated