作者:Jump_jiedB0_666 | 来源:互联网 | 2023-05-16 14:51
IsitpossibleinasqlitedatabasetocraeteatablethathasatimestampcolumnthatdefaulttoDA
Is it possible in a sqlite database to craete a table that has a timestamp column that default to DATETIME('now')
?
是否可以在sqlite数据库中获取具有默认为DATETIME('now')的时间戳列的表?
Like this:
是这样的:
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP DEFAULT DATETIME('now')
);
This gives an error... How to resolve?
这给了一个错误……如何解决?
6 个解决方案
10
This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at
-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.
这是一个完整的例子,基于其他答案和对问题的评论。在本例中,时间戳(created_at-column)被保存为unix纪元UTC时区,并仅在必要时转换为本地时区。
Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.
使用unix epoch保存存储空间- 4字节整数和24字节字符串存储为ISO8601字符串时,请参见数据类型。如果4字节不够,可以增加到6或8字节。
Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.
在UTC时区上保存时间戳可以方便地在多个时区显示合理的值。
SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.
SQLite版本是3.8.6,附带了Ubuntu LTS 14.04。
$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on
create table if not exists example (
id integer primary key autoincrement
,data text not null unique
,created_at integer(4) not null default (strftime('%s','now'))
);
insert into example(data) values
('foo')
,('bar')
;
select
id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;
id|data|epoch |utc |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
Localtime is correct as I'm located at UTC+2 DST at the moment of the query.
Localtime是正确的,因为我在查询时位于UTC+2 DST。