Mysql設定字段自動獲取當前時間的方法

2021-12-30 07:17:00 字數 1267 閱讀 8199

應用場景:

1、在資料表中,要記錄每條資料是什麼時候建立的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄建立時間;

2、在資料庫中,要記錄每條資料是什麼時候修改的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄修改時間;

實現方式:

1、將字段型別設為 timestamp

2、將預設值設為 current_timestamp

舉例應用:

1、mysql 指令碼實現用例

--新增createtime 設定預設時間current_timestamp

alter table `table_name`

add column `createtime` datetime nulldefaultcurrent_timestampcomment '建立時間' ;

--修改createtime設定預設時間current_timestamp

alter table `table_name`

modifycolumn `createtime` datetime nulldefaultcurrent_timestampcomment '建立時間';

--新增updatetime 設定 預設時間current_timestamp 設定更新時間為on updatecurrent_timestamp

alter table `table_name`

add column `updatetime` timestamp nulldefaultcurrent_timestampon updatecurrent_timestampcomment'建立時間' ;

--修改updatetime 設定 預設時間current_timestamp 設定更新時間為on updatecurrent_timestamp

alter table `table_name`

modify column `updatetime` timestamp nulldefaultcurrent_timestampon updatecurrent_timestampcomment'建立時間' ;

2、mysql工具設定

總結:1、mysql自動管理,保持和資料庫時間一致性;

2、簡單高效,不需要應用程式開發支援,mysql自動完成;

Mysql 如何設定字段自動獲取當前時間

問題一 在資料表中,要記錄每條資料是什麼時候建立的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄建立時間 1 將字段型別設為 timestamp 2 將預設值設為 current timestamp 此時,插入資料後 和自增主鍵一樣,無需制定inc time欄位 mysql會自動將i...

Mysql 如何設定字段自動獲取當前時間

應用場景 1 在資料表中,要記錄每條資料是什麼時候建立的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄建立時間 2 在資料庫中,要記錄每條資料是什麼時候修改的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄修改時間 實現方式 1 將字段型別設為 timestamp 2 ...

Mysql 如何設定字段自動獲取當前時間

應用場景 1 在資料表中,要記錄每條資料是什麼時候建立的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄建立時間 2 在資料庫中,要記錄每條資料是什麼時候修改的,不需要應用程式去特意記錄,而由資料資料庫獲取當前時間自動記錄修改時間 實現方式 1 將字段型別設為 timestamp 2 ...