JDBC - Update record example

Posted on February 12, 2017


Technologies used:   JDK 1.8.0_121 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this section, we will show you how to update the database records using the JDBC API. There are four steps for updating a record into a table using JDBC API.

  • Open connection to the database.
  • Create a statement object to perform an update query.
  • Execute the executeUpdate()  method of statement object to submit a SQL query to database.
  • Close connection to the database.

JDBC Statement + Update records example

Here is an example of using the Statement object to update the database records.

UpdateRecordExample1.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class UpdateRecordExample1 {

  public static void main(String[] args) {
    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";
    String sql = "update employee set name='Michael Sam' where emp_id=1";

    try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password); 
        Statement stmt = conn.createStatement();) {
      
      stmt.executeUpdate(sql);
      System.out.println("Database updated successfully ");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

Database updated successfully 

 

JDBC PreparedStatement + Update records example

Here is an example of using the PreparedStatement object to update the database records.

UpdateRecordExample2.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class UpdateRecordExample2 {

  public static void main(String[] args) {
    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";
    String sql = "update employee set name=? where emp_id=?";

    try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
        PreparedStatement stmt = conn.prepareStatement(sql);) {
      stmt.setString(1, "Henry Ellenson");
      stmt.setInt(2, 2);
      stmt.executeUpdate();
      
      System.out.println("Database updated successfully ");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

Database updated successfully