如何用 Java 更新 MySQL 資料庫中的資料?


如需更新 MySQL 資料庫表中的資料,請使用 UPDATE 命令。語法如下:-

update yourTableName set yourColumnName1 = value1,....N where condition;

首先,我們需要建立一個表。查詢如下:-

mysql> create table UpdateDemo
   -> (
   -> id int,
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (0.67 sec)

讓我們向表中插入記錄。查詢如下:-

mysql> insert into UpdateDemo values(101,'John');
Query OK, 1 row affected (0.19 sec)
mysql> truncate table UpdateDemo;
Query OK, 0 rows affected (0.86 sec)
mysql> insert into UpdateDemo values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(2,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(3,'Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into UpdateDemo values(4,'David');
Query OK, 1 row affected (0.15 sec)

現在,藉助 select 語句顯示錶中的所有記錄。查詢如下:-

mysql> select *from UpdateDemo;

以下為輸出:-

+------+-------+
| id   | Name  |
+------+-------+
|    1 | John  |
|    2 | Carol |
|    3 | Smith |
|    4 | David |
+------+-------+
4 rows in set (0.00 sec)

以下是使用 MySQL 資料庫更新記錄的 JAVA 程式碼。我們將為我們的 MySQL 資料庫建立 Java 連線:-

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaUpdateDemo {
   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      try {
         try {
            Class.forName("com.mysql.jdbc.Driver");
         } catch (Exception e) {
            System.out.println(e);
         }
         conn = (Connection) DriverManager.getConnection("jdbc:mysql:///business", "Manish", "123456");
         System.out.println("Connection is created successfully:");
         stmt = (Statement) conn.createStatement();
         String query1 = "update UpdateDemo set Name='Johnson' " + "where id in(1,4)";
         stmt.executeUpdate(query1);
         System.out.println("Record has been updated in the table successfully..................");
      } catch (SQLException excep) {
         excep.printStackTrace();
      } catch (Exception excep) {
         excep.printStackTrace();
      } finally {
         try {
            if (stmt != null)
            conn.close();
         } catch (SQLException se) {}
         try {
            if (conn != null)
            conn.close();
         } catch (SQLException se) {
            se.printStackTrace();
         }
      }
      System.out.println("Please check it in the MySQL Table. Record is now updated.......");
   }
}

以下為輸出:-

我們已使用 id 1 和 4 更新了資料。“Johnson”這一 Name 列已更新。以下是對照查詢,藉助 select 語句查看錶資料是否已更新。

mysql> select *from UpdateDemo;

以下為輸出:-

+------+---------+
| id   | Name    |
+------+---------+
| 1    | Johnson |
| 2    | Carol   |
| 3    | Smith   |
| 4    | Johnson |
+------+---------+
4 rows in set (0.00 sec)

檢視上述輸出,id 1 和 4 已被更新。

更新於:2019 年 7 月 30 日

3 千+ 次瀏覽

開啟你的職業生涯

完成本課程認證

開始學習
廣告