我正在向 QuestDB 中的表发送记录,到目前为止,我有以下内容:
#include <libpq-fe.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
void do_exit(PGconn* conn)
{
PQfinish(conn);
exit(1);
}
int main()
{
PGconn* conn = PQconnectdb(
"host=localhost user=admin password=quest port=8812 dbname=qdb");
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n",
PQerrorMessage(conn));
do_exit(conn);
}
// Simple query
PGresult* res = PQexec(conn,
"CREATE TABLE IF NOT EXISTS trades (ts TIMESTAMP, name STRING, value INT) timestamp(ts);");
PQclear(res);
int i;
for (i = 0; i < 5; ++i) {
char timestamp[30];
char milis[7];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
strftime(timestamp, 30, "%Y-%m-%dT%H:%M:%S.", localtime(&tv.tv_sec));
snprintf(milis, 7, "%d", tv.tv_usec);
strcat(timestamp, milis);
const char* values[1] = { timestamp };
int lengths[1] = { strlen(timestamp) };
int binary[1] = { 0 };
res = PQexecParams(conn,
"INSERT INTO trades VALUES (to_timestamp($1, 'yyyy-MM-ddTHH:mm:ss.SSSUUU'), 'timestamp', 123);",
1, NULL, values, lengths, binary, 0);
}
res = PQexec(conn, "COMMIT");
printf("Done\n");
PQclear(res);
do_exit(conn);
return 0;
}
这个问题是我在字符串转换上做了很多杂耍,然后最终使用to_timestamp()。我想摆脱这个并PQexecParams
以简洁的方式直接插入值。
据我所知,Postgres 文档中的 PQexecParams示例并未提供有关如何使用时间戳或日期类型的任何指导。