连接postgresql的C字符串

时间:2013-02-26 03:14:31

标签: c postgresql

所以我试图在for循环中构建我的sql语句 但在执行时,它会在字符串的第一个点显示错误 连接方法是错误的,因为我打印了sql语句并在postgresql中手动执行它可以工作。

我也试过

char *sqlStatement = "INSERT INTO record()..VALUES();\
    INSERT INTO record()..VALUES();\
    INSERT INTO record()..VALUES();
"

有效。

请注意,我已将循环缩减为仅一次,并为了简洁而减少了列数。

代码:

char sqlStatement[8000];
for(int i=0;i<1;i++) {
        sprintf(&sqlStatement[0] + strlen(sqlStatement), "INSERT INTO record (\"user_id\", \"filename\", \"ports\", \"timestamp\" ... )VALUES (1, 'example%d', 0, '123456789%d', ... );", i, i,);
}
pgResult = PQexec(pgConn, sqlStatement);
if (PQresultStatus(pgResult) != PGRES_COMMAND_OK) {
        printf("%s", PQresultErrorMessage(pgResult));
        PQclear(pgResult);
        closeSQL(pgConn);
        exit(-1);
}

错误讯息:

ERROR:  syntax error at or near ""
LINE 1: INSERT INTO captures ("user_id", "filename", "ports", "time...        
        ^

2 个答案:

答案 0 :(得分:1)

您正在呼叫strlen(sqlStatement),但此时sqlStatement未初始化。这是未定义的行为。

sqlStatement[0] = '\0';

在循环之前用空字符串开始。

顺便说一句,exit(-1)是错误的。唯一的标准C退出值为0 / EXIT_SUCCESSEXIT_FAILURE。在Unix上,您可以使用0255之间的任何值。我不确定Windows,但它可能类似。我不知道-1有效的任何操作系统。

答案 1 :(得分:0)

char sqlStatement[11111];
size_t_pos;

pos=0; 
pos += sprintf(sqlStatement+pos, "INSERT INTO record() VALUES(%s);\n" , "Argh!" );
pos += sprintf(sqlStatement+pos, "INSERT INTO record(...);\n" ... );
pos += sprintf(sqlStatement+pos, "INSERT INTO record(...);\n" ... );
...

真正的程序当然应首先检查sprintf的返回值,然后再使用它来增加pos位置。