我想在SQLite中创建一个表格,其中一个字段是日期,应该保存当前实例的日期和时间。我应该使用什么数据类型?
我计划使用“timestamp”。如何将当前时间戳值插入到字段中?还有如何编写与此日期字段相关的内容值?
我想在SQLite中创建一个表格,其中一个字段是日期,应该保存当前实例的日期和时间。我应该使用什么数据类型?
我计划使用“timestamp”。如何将当前时间戳值插入到字段中?还有如何编写与此日期字段相关的内容值?
SQLite支持标准SQL变量CURRENT_DATE
、CURRENT_TIME
和CURRENT_TIMESTAMP
:
INSERT INTO Date (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
在SQLite中,默认的日期/时间数据类型是TEXT
。
ContentValues
不允许使用通用SQL表达式,只能使用固定值,因此您需要在Java中读取当前时间:
cv.put("LastModifiedTime",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
INSERT INTO Date (LastModifiedTime) VALUES(DateTime('now'))
请使用此网站以供参考。
要获取当前本地(系统)时间,请添加'localtime'选项:
select datetime('now', 'localtime');
ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());
在我的情况下,我想要一个带有秒的小数部分的时间戳。
CURRENT_TIMESTAMP
只有精度为 YYYY-MM-DD HH:MM:SS
(请参见 文档 DEFAULT 子句)。strftime()
可以返回秒的小数部分。strftime()
在 INSERT
中的示例INSERT INTO YourTable (TimeStamp)
VALUES (strftime('%Y-%m-%d %H:%M:%S:%s'))
CURRENT_TIMESTAMP
和strftime()
的比较SELECT 'CURRENT_TIMESTAMP' as Timestamp_Command,
CURRENT_TIMESTAMP as TimeStamp_Precision,
'only seconds' as Timestamp_Comment
UNION ALL
SELECT 'strftime(%Y-%m-%d %H:%M:%S:%s)' as Timestamp_Command,
(strftime('%Y-%m-%d %H:%M:%S:%s')) as TimeStamp_Precision,
'with fraction of a second' as Timestamp_Comment
以下内容基于使用ADO.NET进行SQLite批量插入。
public static void InsertBulk(SqliteConnection connection)
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var command = connection.CreateCommand();
command.CommandText =
@"INSERT INTO BulkInsertTable (CreatedOn, TimeStamp)
VALUES ($createdOn, strftime('%Y-%m-%d %H:%M:%S:%s'))";
var parameter3 = command.CreateParameter();
parameter3.ParameterName = "$createdOn";
command.Parameters.Add(parameter3);
// Insert a lot of data
// calling System.DateTime.Now outside the loop is faster
var universalTime = System.DateTime.Now.ToUniversalTime();
for (var i = 0; i < 15_000; i++)
{
parameter3.Value = System.DateTime.Now.ToUniversalTime();
// faster
// parameter3.Value = universalTime;
command.ExecuteNonQuery();
}
transaction.Commit();
}
connection.Close();
}