JDBC Statement Update record example

JDBC Statement Update record example

By Yashwant Chavan, Views 852, Date 02-Jun-2012

Jdbc Statement Update record example

tags java

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
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]