0

我正在向 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示例并未提供有关如何使用时间戳或日期类型的任何指导。

4

1 回答 1

1

你做得对。

准备好的语句的参数可以像您正在做的那样以文本格式发送,也可以以二进制格式发送。对于二进制格式,您必须设置

int binary[1] = { 1 };

并将时间戳转换为内部 PostgreSQL 格式。在timestampor的情况下timestamp with time zone,这是一个 8 字节整数(按网络字节顺序),包含自 以来的微秒数2000-01-01 00:00:00

我想将时间戳转换为该格式并不会简单得多,因此您不会获得很多收益,但最终得到的代码可能取决于服务器机器的体系结构。

于 2021-02-22T18:39:29.007 回答