向 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 千次以上浏览

开启你的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.