Update Records

Update Records

In this tutorial, we are going to discuss about how to update records into table using JDBC. Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

Here’s a simple example of Update Records using JDBC (Java Database Connectivity). In this example, I’ll demonstrate how to connect to a MySQL database and update records into the table named “employees” with three columns: “id”, “name”, and “salary”.

Update Records

Updating records in a table using JDBC involves similar steps to inserting records. Here’s a basic example demonstrating how to update records using JDBC:

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

public class UpdateExample {

    public static void main(String[] args) {
        // JDBC URL, username, and password for your database
        String url = "jdbc:mysql://localhost:3306/employee";
        String user = "ashok";
        String password = "Ashok@123";

        // SQL UPDATE statement
        String updateSQL = "UPDATE your_table_name SET name = ?, salary = ? WHERE id = ?";

        try (
            // Establishing connection to the database
            Connection connection = DriverManager.getConnection(url, user, password);
            // Creating a prepared statement
            PreparedStatement preparedStatement = connection.prepareStatement(updateSQL)
        ) {
            // Setting new values for placeholders (?)
            preparedStatement.setString(1, "Ashok Kumar");
            preparedStatement.setString(2, 83000);
            preparedStatement.setInt(3, 87); // Assuming 'id' is the primary key column

            // Executing the UPDATE statement
            int rowsAffected = preparedStatement.executeUpdate();

            System.out.println(rowsAffected + " row(s) updated successfully.");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Replace "employee", "ashok", "Ashok@143", "employee", "name", "salary", and "id" with your actual database name, username, password, table name, column names, and the primary key column name, respectively.

Ensure that:

  • You have the appropriate permissions to update records in the table in the database.
  • Handle exceptions properly, especially when dealing with database operations. In this example, exceptions are simply printed, but in a real application, you would handle them more robustly, possibly logging them or presenting meaningful error messages to the user.
  • Use PreparedStatement to safely update values in the SQL statement and prevent SQL injection attacks.

That’s all about the how to update records into table using JDBC. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Update Records
Scroll to top