Home  >  Q&A  >  body text

mysql的insert语句怎么插入当前时间?

mysql的insert语句怎么插入当前时间?

比如有一张表users,有id,name,eamil,password,created_at,updated_at字段。
我想插入一条数据,这样写:

INSERT INTO users VALUES (Null, 'xiaoming','xiaoming@example.com','ffahifuhaif','','' );

问题:
1、id是自增长的,上面语句中id字段写Null正确么?
2、created_at,updated_at两个字段要插入当前时间,应该怎么做?

天蓬老师天蓬老师2742 days ago1035

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-04-17 16:38:33

    1. Your grammar is wrong. INSERT INTO table_name (column 1, column 2,...) VALUES (value 1, value 2,....)
    ID does not need to be written in, it will be assigned automatically.

    2. The time field can also automatically insert the current time with default value.
    http://s11.sinaimg.cn/mw690/0...

    The field type is set to timestamp, and the default value is CURRENT_TIMESTAMP

    When inserting data, the time will be automatically saved in this field.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 16:38:33

    1. For fields set to auto_increase, it is useless for you to set other values.

    2. If you use php, insert the current time using NOW();

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:38:33

    You can leave unnecessary fields blank

        INSERT INTO users(name,eamil,password) VALUES ( 'xiaoming','xiaoming@example.com','ffahifuhaif');

    There are two other time issues, which can be set like this in the database:

    1. created_at default value is set to CURRENT_TIMESTAMPcreated_at 默认值设置为 CURRENT_TIMESTAMP

    2. updated_at 默认值设置为 CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

    updated_at The default value is set to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP


    🎜Requires mysql version to be greater than 5.6.5🎜According to this http://stackoverflow.com/a/4897134🎜

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 16:38:33

    First determine what data type your time is stored in. Is it int? date? Or timestamp? datetime? Then process it according to the specific type

    reply
    0
  • Cancelreply