Update Query in MySQL using Java PreparedStatement

In this article, we will learn how to update a record in a MySQL database table using the JDBC PreparedStatement interface.

As we know PreparedStatement interface improves performance like SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Java JDBC PreparedStatement Update a Record Example

In this example, we will use the users database table. Before updating a record to a database, Make sure that you need to first create a users table and insert some records in a database. 
In the following example, we will update the user name from "Ramesh" to "Ram":
package com.javaguides.jdbc.preparestatement.examples; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /**  * Update PreparedStatement JDBC Example  * @author Ramesh Fadatare  *  */ public class UpdatePStatementExample { private static final String UPDATE_USERS_SQL = "update users set name = ? where id = ?;"; public static void main(String[] argv) throws SQLException { UpdatePStatementExample updateStatementExample = new UpdatePStatementExample(); updateStatementExample.updateRecord(); } public void updateRecord() throws SQLException { System.out.println(UPDATE_USERS_SQL); // Step 1: Establishing a Connection try (Connection connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root"); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) { preparedStatement.setString(1, "Ram"); preparedStatement.setInt(2, 1); // Step 3: Execute the query or update query preparedStatement.executeUpdate(); } catch (SQLException e) { // print SQL exception information printSQLException(e); } // Step 4: try-with-resource statement will auto close the connection. } public static void printSQLException(SQLException ex) { for (Throwable e: ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }

Output

References

https://www.javaguides.net/2018/10/jdbc-preparedstatement-update-record-example.html


Comments