JDBC PreparedStatement – Update a row

A JDBC PreparedStatement example to update a row.

RowUpdate.java

package com.mkyong.jdbc.preparestatement.row;

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

public class RowUpdate {

    private static final String SQL_UPDATE = "UPDATE EMPLOYEE SET SALARY=? WHERE NAME=?";

    public static void main(String[] args) {

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             PreparedStatement preparedStatement = conn.prepareStatement(SQL_UPDATE)) {

            preparedStatement.setBigDecimal(1, new BigDecimal(999.99));
            preparedStatement.setString(2, "mkyong");

            int row = preparedStatement.executeUpdate();

            // 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();
        }

    }

}

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
8 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
David WellbornriyaJisa Maria JamesonAndrey StepanovJack the Newbie Recent comment authors
newest oldest most voted
HoangLe
Guest
HoangLe

Your code will always show: Record is updated to DBUSER table even though it doesn’t update. you have to get the int value that is returned from executeUpdate() and throws exception if the return value is 0. Your try catch only check SQL syntax.

David Wellborn
Guest
David Wellborn

You should close the preparedStatement and the conn objects in a finally block for completeness. Otherwise, you leak resources everytime this is called.

riya
Guest
riya

“update signupform ”
+ “set ? = ? ”
+ “where ”
+ “contact = ? “;
Will it work??

Jisa Maria Jameson
Guest
Jisa Maria Jameson

Thank you. Was helpful to do my project

Andrey Stepanov
Guest
Andrey Stepanov

What does this line do: Class.forName(DB_DRIVER)?

Why does it neither return anything nor create a new instance of a driver like: Class.forName(DB_DRIVER).newIntsance()?

What driver the DriverManager will use when calling getConnection()?

Thank you

Jack the Newbie
Guest
Jack the Newbie

Boy, you do a great job! Thanks

kush
Guest
kush

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.util.logging.Level; import java.util.logging.Logger; import java.sql.*; import java.util.Scanner; /** * * @author 3ce75 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { Class.forName(“org.apache.derby.jdbc.ClientDriver”); } catch (ClassNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } String url=”jdbc:derby://localhost:1527/db”; String un=”d”; String pwd=”b”; try { Connection cn = DriverManager.getConnection(url, un, pwd); int choice; System.out.println(“enter your choice”); Scanner sn=new Scanner(System.in); choice=sn.nextInt(); String query; switch(choice) { case 1: query=”insert into db (id,name,mobile) values(?,?,?)”;… Read more »

zahid se
Guest
zahid se

this website is my favorite website i really say thanks to this web site developers .