How does Mysql set the field to automatically obtain the current time?

Source: Internet
Author: User

How does Mysql set the field to automatically obtain the current time?

Application scenarios:

 

1. In a data table, to record when each piece of data was created, the data database automatically records the creation time without the need for the application to specifically record it;

2. In the database, when is each data record modified? The data database obtains the current time to automatically record the modification time without the need for the application to specifically record it;

 

Implementation Method:

 

1. Set the field type to TIMESTAMP.

2. Set the default value to CURRENT_TIMESTAMP.

 

Example application:

 

1. MySQL script implementation case

-- Add CreateTime to set the default time CURRENT_TIMESTAMP

Alter table 'table _ name'
Add column 'createtime' datetime null default CURRENT_TIMESTAMP comment' creation time ';

 

-- Modify the default time of CreateTime settings CURRENT_TIMESTAMP
Alter table 'table _ name'
Modify column 'createtime' datetime null default CURRENT_TIMESTAMP COMMENT 'creation time ';

 

-- Add UpdateTime to set the default time CURRENT_TIMESTAMP to set the UPDATE Time To on update CURRENT_TIMESTAMP
Alter table 'table _ name'
Add column 'updatetime' timestamp null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT 'creation time ';

 

-- Modify UpdateTime to set the default time CURRENT_TIMESTAMP and set the UPDATE Time To on update CURRENT_TIMESTAMP.

Alter table 'table _ name'
Modify column 'updatetime' timestamp null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT 'creation time ';

2. MySQL tool settings

 

 

Summary:

 

1. MySQL is automatically managed to maintain time consistency with the database;

2. Simple and efficient. MySQL is automatically completed without application development support;

View comments

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.