Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Java Database Connectivity (JDBC)

Updating Data using JDBC

Using Statement:

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

Steps to Execute an UPDATE 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 UPDATE query using the Statement.

Example Code using Statement (Java):

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

public class StatementUpdateExample {
    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 = "UPDATE users SET age = 35 WHERE id = 1";
            int rowsAffected = statement.executeUpdate(sqlQuery);

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

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

Using PreparedStatement:

  • PreparedStatement is used for executing parameterized SQL queries.

Steps to Execute an UPDATE 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):

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

public class PreparedStatementUpdateExample {
    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 = "UPDATE users SET age = ? WHERE id = ?";
            int newAge = 40;
            int userId = 2;

            try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
                preparedStatement.setInt(1, newAge);
                preparedStatement.setInt(2, userId);

                int rowsAffected = preparedStatement.executeUpdate();

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

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

Explanation:

  • StatementUpdateExample: Uses Statement to update the age of the user with ID 1 to 35.

  • PreparedStatementUpdateExample: Uses PreparedStatement to update the age of the user with a specific ID. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.

PreviousInserting Data using JDBCNextDeleting Data using JDBC

Last updated 1 year ago