Computer >> Computer tutorials >  >> Programming >> MySQL

Update a MySQL table with Java MySQL


For this, you need to use PreparedStatement in Java for update. Let us first create a table −

mysql> create table DemoTable(
   Id int,
   FirstName varchar(40)
);
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(111,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(121,'Sam');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Chris     |
| 111  | Mike      |
| 121  | Sam       |
+------+-----------+
3 rows in set (0.00 sec)

The Java code is as follows to update −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UpdateFromJava {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      try {
         con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?" +
         "useSSL=false", "root", "123456");
         String query = "update DemoTable set FirstName=? where Id=? ";
         ps = con.prepareStatement(query);
         ps.setString(1, "Tom");
         ps.setInt(2, 100);
         ps.executeUpdate();
         System.out.println("Record is updated successfully......");
         } catch (Exception e) {
            e.printStackTrace();
      }
   }
}

Following the output of Java code −

Record is updated successfully......

The screenshot of the output is as follows −

Update a MySQL table with Java MySQL

Let us now check the FirstName column name value has been updated to ‘Tom’ or not with ID 100.

Following is the query to check records and display them again −

mysql> select * from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  |       Tom |
| 111  |      Mike |
| 121  |       Sam |
+------+-----------+
3 rows in set (0.00 sec)

The snapshot of the output is as follows. The FirstName column updated successfully with Java-MySQL −

Update a MySQL table with Java MySQL