【问题标题】:How do I insert a timestamp in a prepared statement via postgres?如何通过 postgres 在准备好的语句中插入时间戳?
【发布时间】:2021-02-22 16:38:09
【问题描述】:

我正在向 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期间插入值。

据我所知,PQexecParams in the Postgres docs 显示的示例并未提供有关如何使用时间戳或日期类型的任何指导。

【问题讨论】:

    标签: c++ postgresql questdb


    【解决方案1】:

    你做得对。

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

    int binary[1] = { 1 };
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2014-10-14
      • 2013-09-18
      • 2020-08-20
      相关资源
      最近更新 更多