Sqlite:如何从C++绑定和插入日期?

Use*_*ser 5 c++ sql sqlite datetime insert

使用C++(Visual Studio)和sqlite.如何将日期绑定到参数?

sqlite3_stmt *statement;

const char *sql = 
    "INSERT INTO employees "
        "(full_name,"
        "date_started)" 
    " VALUES "
        "(@full_name,"
        "@date_started)";

sqlite3_prepare_v2(database_, sql, -1, &statement, NULL);

int parameterIndex = sqlite3_bind_parameter_index(statement, "@full_name");
sqlite3_bind_text(statement, parameterIndex, "John Smith", -1, SQLITE_TRANSIENT);

parameterIndex = sqlite3_bind_parameter_index(statement, "@date_started");

// <??? what goes here ???>
// I want to include the local current time, so I want to know:
// 1. what's the best way to get local time in C++
// 2. and what goes here for the date binding

sqlite3_step(statement);

sqlite3_finalize(statement);
Run Code Online (Sandbox Code Playgroud)

注意:我不想使用sql设置当前时间(例如,CURRENT_TIMESTAMP等)

Don*_*eba 8

它没有诀窍:

const char * sql =
    "INSERT INTO Employees(full_name, data_started) VALUES (?, ?)";
time_t time = 0x3DE43B0C;
sqlite3_bind_int64(statement, 2, time);
Run Code Online (Sandbox Code Playgroud)

以下是文档的相关部分:

1.1日期和时间数据类型

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

  • TEXT为ISO8601字符串("YYYY-MM-DD HH:MM:SS.SSS").
  • 真实如朱利安日数,根据公历4714年11月24日格林威治中午以来的天数.
  • INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数.

应用程序可以选择以任何这些格式存储日期和时间,并使用内置的日期和时间函数在格式之间自由转换.


Use*_*ser 0

这就是我的想法。它有效,但我愿意接受更好的方法。

time_t rawtime;
struct tm *currentTime;
time ( &rawtime );
currentTime = localtime ( &rawtime );

const int TIME_STRING_LENGTH = 20;
char buffer [TIME_STRING_LENGTH];

// SQLite expected date string format is "YYYY-MM-DD HH:MM:SS" (there are others too)
strftime(buffer, TIME_STRING_LENGTH, "%Y-%m-%d %H:%M:%S", currentTime);
sqlite3_bind_text(statement, parameterIndex, buffer, -1, SQLITE_TRANSIENT);
Run Code Online (Sandbox Code Playgroud)

  • 更喜欢使用“gmtime”而不是“localtime”,因为它对夏令时不敏感。 (2认同)