是否可以在sqlite数据库中创建一个具有默认为 DATETIME('now')的时间戳列的表?

像这样:

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t TIMESTAMP DEFAULT DATETIME('now')
);

这会出错...如何解决?

有帮助吗?

解决方案

我相信你可以使用

CREATE TABLE test (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  t TIMESTAMP
  DEFAULT CURRENT_TIMESTAMP
);

3.1版(来源

其他提示

据博士说。 hipp在最近的一个帖子中发布:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

这只是一个语法错误,你需要括号:(DATETIME('now'))

如果你查看文档,你会注意到括号在语法中的'expr'选项周围添加。

这是基于问题的其他答案和评论的完整示例。在示例中,时间戳( created_at -column)保存为 unix epoch UTC时区,仅在必要时转换为本地时区。

使用unix epoch可以节省存储空间 - 当存储为ISO8601字符串时,整数为4个字节,而24个字节为字符串,请参阅数据类型的。如果4个字节不够,可以增加到6或8个字节。

在UTC时区保存时间戳可以方便地在多个时区显示合理的值。

SQLite版本是随Ubuntu LTS 14.04一起提供的3.8.6。

$ 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是正确的,因为我在查询时位于UTC + 2 DST。

使用REAL类型可能更好,以节省存储空间。

引用 SQLite版本3中的数据类型的1.2部分

  

SQLite没有为存储日期留出的存储类   和/或时间。相反,SQLite的内置日期和时间函数   能够将日期和时间存储为TEXT,REAL或INTEGER   值

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

请参阅列限制

插入一行而不提供任何价值。

INSERT INTO "test" DEFAULT VALUES;

这是语法错误,因为您没有写括号

如果你写

  

选择日期时间('现在')   然后它会给你utc时间,但如果你这样写它查询,那么你必须在此之前添加括号   所以(datetime('now'))表示UTC时间。   当地时间相同   选择datetime('now','localtime')   查询

(日期时间( '现在', '本地时间'))

此替代示例将本地时间存储为Integer以保存20个字节。该工作在字段默认,Update-trigger和View中完成。 strftime必须使用'%s'(单引号),因为“%s” (双引号)对我犯了一个'Not Constant'错误。

Create Table Demo (
   idDemo    Integer    Not Null Primary Key AutoIncrement
  ,DemoValue Text       Not Null Unique
  ,DatTimIns Integer(4) Not Null Default (strftime('%s', DateTime('Now', 'localtime'))) -- get Now/UTC, convert to local, convert to string/Unix Time, store as Integer(4)
  ,DatTimUpd Integer(4)     Null
);

Create Trigger trgDemoUpd After Update On Demo Begin
  Update Demo Set
    DatTimUpd  =                          strftime('%s', DateTime('Now', 'localtime'))  -- same as DatTimIns
  Where idDemo = new.idDemo;
End;

Create View If Not Exists vewDemo As Select -- convert Unix-Times to DateTimes so not every single query needs to do so
   idDemo
  ,DemoValue
  ,DateTime(DatTimIns, 'unixepoch') As DatTimIns -- convert Integer(4) (treating it as Unix-Time)
  ,DateTime(DatTimUpd, 'unixepoch') As DatTimUpd --   to YYYY-MM-DD HH:MM:SS
From Demo;

Insert Into Demo (DemoValue) Values ('One');                      -- activate the field Default
-- WAIT a few seconds --    
Insert Into Demo (DemoValue) Values ('Two');                      -- same thing but with
Insert Into Demo (DemoValue) Values ('Thr');                      --   later time values

Update Demo Set DemoValue = DemoValue || ' Upd' Where idDemo = 1; -- activate the Update-trigger

Select * From    Demo;                                            -- display raw audit values
idDemo  DemoValue  DatTimIns   DatTimUpd
------  ---------  ----------  ----------
1       One Upd    1560024902  1560024944
2       Two        1560024944
3       Thr        1560024944

Select * From vewDemo;                                            -- display automatic audit values
idDemo  DemoValue  DatTimIns            DatTimUpd
------  ---------  -------------------  -------------------
1       One Upd    2019-06-08 20:15:02  2019-06-08 20:15:44
2       Two        2019-06-08 20:15:44
3       Thr        2019-06-08 20:15:44
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top