如果 MySQL 中存在一張表,則向該表中插入資料,否則執行 CREATE TABLE 並建立該表


以下是如何檢查表是否已使用 CREATE TABLE IF NOT EXISTS 生成的−

create table if not exists yourTableName
(
   yourColumnName1 dataType,
   .
   .
   .
   .
   N
);
insert into yourTableName values(yourValue1,.......N);

讓我們首先建立一個表−

mysql> create table if not exists DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentSubject varchar(100)
);
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些記錄−

mysql> insert into DemoTable(StudentSubject) values('Java');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(StudentSubject) values('MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentSubject) values('C');
Query OK, 1 row affected (0.23 sec)

使用 select 語句顯示錶中的所有記錄−

mysql> select *from DemoTable;

這將產生以下輸出 −

+-----------+----------------+
| StudentId | StudentSubject |
+-----------+----------------+
|         1 | Java           |
|         2 | MySQL          |
|         3 | C              |
+-----------+----------------+
3 rows in set (0.00 sec)

更新日期: 2019 年 9 月 26 日

986 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.