向 MySQL 資料庫中插入當前日期?


要將當前日期插入資料庫,可以使用 NOW()。以下是語法 −

INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW());

如果你的列有資料型別 date,那麼 NOW() 函式只插入當前日期,不插入時間,並且 MySQL 將會給予一個警告。要移除該警告,可以使用 CURDATE()。

讓我們首先建立一個表 −

mysql> create table insertcurrentdate
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> currentDate date
   -> );
Query OK, 0 rows affected (1.09 sec)

以下是使用 insert 命令在表中插入一些記錄的查詢。我們使用 NOW() 和 CURDATE() 來顯示當前日期 −

mysql> insert into insertcurrentdate(currentDate) values(NOW());
Query OK, 1 row affected, 1 warning (0.24 sec)

mysql> insert into insertcurrentdate(currentDate) values(CURDATE());
Query OK, 1 row affected (0.18 sec)

以下是使用 select 語句從表中顯示所有記錄的查詢 −

mysql> select * from insertcurrentdate;

這將產生以下輸出 −

+----+-------------+
| Id | currentDate |
+----+-------------+
| 1  | 2019-04-05  |
| 2  | 2019-04-05  |
+----+-------------+
2 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

4 千次以上瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告