2008-10-14 75 views
142

是否有可能在sqlite数据库craete具有默认为DATETIME('now')时间戳列的表?sqlite数据库默认时间值'现在'

像这样:

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

这给出了一个错误......如何解决?

回答

222

我相信你可以使用

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

为3.1版根据博士(source

+13

如果您关心存储大小,请注意,此配方会将您的时间戳保存为ISO-8601(文本格式),每个日期在数据库中占用大约24个字节。您可以通过使用INTEGER(4)列来节省空间,并通过“INSERT INTO test(t)values(strftime(”%s“,CURRENT_TIME))来存储unix时间;” – mckoss 2012-02-05 08:17:08

+2

@mckoss感谢您的评论,创建声明成为:... mycolumn默认(strftime('%s','now')) – larham1 2012-06-15 06:41:42

+1

“... default(strftime('%s','now')) “不是常量表达式,使用默认赋值时不起作用”错误:列[...]的默认值不是常量“。 – 2012-08-04 22:35:10

71

。 HIPP在最近的名单张贴:

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

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

如果你看一下documentation,你会注意到,围绕“expr的”添加括号选项的语法。

3

这是语法错误,因为你,如果你写

Select datetime('now') then it will give you utc time but if you this write it query then you must add parenthesis before this so (datetime('now')) for UTC Time. for local time same Select datetime('now','localtime') for query

没有写括号

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

3

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

报价从1.2部分的Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

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

看到column-constraint

insert一排没有提供任何价值。

INSERT INTO "test" DEFAULT VALUES; 
9

这是一个基于其他问题的答案和评论的完整示例。在该示例中,时间戳记(created_at栏位)被保存为UTC时区的unix epoch,并仅在必要时才转换为本地时区。

使用unix时间节省存储空间 - 存储为ISO8601字符串时,4字节整数与24字节字符串相比,请参见datatypes。如果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。