JDBC Statement – Update a row

A JDBC Statement example to update a row.

RowUpdate.java

package com.mkyong.jdbc.statement.row;

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

public class RowUpdate {

    public static void main(String[] args) {

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement()) {

            int row = statement.executeUpdate(updateSalaryByName("mkyong", new BigDecimal(1080)));

            // rows affected
            System.out.println(row);


        } catch (SQLException e) {
            System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static String updateSalaryByName(String name, BigDecimal salary) {

        return "UPDATE EMPLOYEE SET SALARY='" + salary + "' WHERE NAME='" + name + "'";

    }
}

P.S Tested with PostgreSQL 11 and Java 8

pom.xml

	<dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency>

Download Source Code

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
akita noqsandeep akular Recent comment authors
newest oldest most voted
r
Guest
r

update table_users set status =? where user_id=?
how i can do it by prepare statement? plz help

sandeep akula
Guest
sandeep akula

im struck with the same too

akita noq
Guest
akita noq

String SQL_UPDATE=”update table_users set status =? where user_id=?”;
PreparedStatement preparedStatement = c.prepareStatement(SQL_UPDATE);
preparedStatement.setString(1, “inactivo”); // status
preparedStatement.setString(2, “5”); //user id
int row = preparedStatement.executeUpdate();