JDBC Statement Update record example

Jdbc Statement Update record example

Jdbc Statement Update record example

package com.technicalkeeda.jdbc;

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

public class JdbcUpdateExample {

    public static void main(String[] args) {

        JdbcUpdateExample example = new JdbcUpdateExample();
        example.update();
    }

    public void update() {

        Statement statement = null;
        Connection connection = null;
        try {

            connection = getConnection();
            statement = connection.createStatement();

            String sql = "update trn_employee set first_name='Yashwant Updated' where emp_id = 1";

            int affectedRecords = statement.executeUpdate(sql);
            System.out.println("Number of Records Updated:- " + affectedRecords);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }

    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/technicalkeeda", "root", "");

        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return connection;
    }
}

Output

Number of Records Updated:- 1