1、datetime,date,time,year四个类型的值,可以手动输入,也可以调用函数获得值
① 手动输入,格式如下:
datetime "2016-6-22 14:09:30"
date "2016-6-22"
time "14:09:30"
year "2016"
如上所述,手动输入的时候,直接可以输入如上格式的字符串,注意需要加引号。其中日期和时间中的分隔符(日期的短横线"-",时间的冒号":"),都可以用别的符号来代替,如“2016/6/22 14/9/30”
② 用函数获取值,可以直接使用now()函数来获取当前的时间
2、timestamp类型的值,可以不用输入,数据库会自动填充
示例代码:
/*创建表*/mysql> create table time_table( -> dt datetime, -> d date, -> t time, -> y year, -> ts timestamp -> ); Query OK, 0 rows affected (0.05 sec) /*查看表结构*/ mysql> desc time_table; +-------+-----------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +-------+-----------+------+-----+-------------------+-----------------------------+ | dt | datetime | YES | | NULL | | | d | date | YES | | NULL | | | t | time | YES | | NULL | | | y | year(4) | YES | | NULL | | | ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | +-------+-----------+------+-----+-------------------+-----------------------------+ 5 rows in set (0.01 sec) /*手动插入数据,ts数据为null*/ mysql> insert into time_table(dt,d,t,y,ts) values("2016-6-22 11:57:30","2016/6/22","11:57:30","2016",null); Query OK, 1 row affected (0.01 sec) /*手动插入数据,没有为ts提供数据*/ mysql> insert into time_table(dt,d,t,y) values("2016-6-22 11:57:30","2016/6/22","11:57:30","2016"); Query OK, 1 row affected (0.00 sec) /*利用now()函数提供数据,为y字段手动输入数据,没有为ts提供数据*/ mysql> insert into time_table(dt,d,t,y) values(now(),now(),now(),‘2016‘); Query OK, 1 row affected, 1 warning (0.00 sec) /*手动插入数据,日期时间分隔符更换为“/”,依然没有为ts提供数据*/ mysql> insert into time_table(dt,d,t,y) values ("2016/6/22 14/10/30","2016/6/22","14:10:30","2016"); Query OK, 1 row affected (0.00 sec) /*查看数据*/ mysql> select * from time_table; +---------------------+------------+----------+------+---------------------+ | dt | d | t | y | ts | +---------------------+------------+----------+------+---------------------+ | 2016-06-22 11:57:30 | 2016-06-22 | 11:57:30 | 2016 | 2016-06-22 11:58:00 | | 2016-06-22 11:57:30 | 2016-06-22 | 11:57:30 | 2016 | 2016-06-22 11:59:05 | | 2016-06-22 13:58:54 | 2016-06-22 | 13:58:54 | 2016 | 2016-06-22 13:58:54 | | 2016-06-22 14:10:30 | 2016-06-22 | 14:10:30 | 2016 | 2016-06-22 14:11:58 | +---------------------+------------+----------+------+---------------------+ 4 rows in set (0.00 sec)
时间: 2024-10-09 01:34:20