Mysql-default a date (timestamp) field to now

Source: Internet
Author: User
Tags mysql insert timestamp example

MySQL date syntax faq:how do I set a MySQL date field to default to ' now ', i.e.

Setting the date to ' now '

Unfortunately you can ' t default a MySQL DATE field to "Now", but can get the "now" behavior with a MySQL TIMESTAMP fie Ld. The syntax to create a MySQL TIMESTAMP ' Now ' field is:

last_changed timestamp NOT NULL default now (),

  

Where is the last_changed name of my field, is the timestamp type of field, it can ' t be null, and the date/time default is now() .

Now if you did a MySQL insert, just skip this field in your MySQL INSERT statement, and this field would default to the CU Rrent Date/time.

Example

To is clear about what this works, here's a complete example of what to the default a MySQL timestamp field to "Now":

Mysql> CREATE TABLE Test (foo int, ts timestamp default now ()); Query OK, 0 rows affected (0.20 sec) mysql> desc test;+-------+-----------+------+-----+-------------------+-------+ | Field | Type      | Null | Key | Default           | Extra |+-------+-----------+------+-----+-------------------+-------+| Foo   | int   | YES  |     | NULL              | |       | TS    | timestamp | NO   |     | Current_timestamp |       | +-------+-----------+------+-----+-------------------+-------+2 rows in Set (0.02 sec) mysql> insert into Test (foo) VALUES (1); Query OK, 1 row affected (0.03 sec) mysql> select * from test;+------+---------------------+| Foo  | ts                  |+------+---------------------+|    1 | 2010-12-15 14:20:59 |+------+---------------------+1 row in Set (0.02 sec)

  

Summary

I Hope this MySQL timestamp example have been helpful. As usual, if you had any questions or comments, just leave a note below.

Mysql-default a date (timestamp) field to now

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.