0
#include <iostream>
#include "libpq-fe.h"
using namespace std;
void CloseConn(PGconn *conn)
{
    PQfinish(conn);
    getchar();
}

PGconn *ConnectDB()
{
    PGconn *conn = NULL;

    // Make a connection to the database
    conn = PQconnectdb("user=postgres password=password dbname=postgres hostaddr=192.168.xxx.xxx port=5432");

    // Check to see that the backend connection was successfully made
    if (PQstatus(conn) != CONNECTION_OK)
    {
        cout << "Connection to database failed.\n";
        CloseConn(conn);
    }
    cout << "Connection to database - OK\n";
    return conn;
}


void InsertEmployeeRec(PGconn *conn)
{
    int nFields;
    // Append the SQL statment
    std::string sSQL;

    // problem start-------------------------
    for(int i=0;i<10;i++)
    {
        sSQL.append("INSERT INTO test(lat,lng) VALUES (i,20)");
    }
    //problem end----------------------------

    // Execute with sql statement
    PGresult *res = PQexec(conn, sSQL.c_str()); 

    if (PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        cout << "Insert test record failed\n";
        PQclear(res);
        CloseConn(conn);
    }

    cout << "Insert test record     - OK";

    // Clear result
    PQclear(res);
}

int main(int argc, char *argv[ ])
{
    PGconn *conn = NULL;

    conn = ConnectDB();

    if (conn != NULL)
    {
        InsertEmployeeRec(conn);

        CloseConn(conn);
    }
    return 0;
}

并在终端

alan@alan-virtual-machine:~/文件$ g++ ex6.cpp -I /usr/include/postgresql -l pq -o ex6
alan@alan-virtual-machine:~/文件$ ./ex6
Connection to database - OK
Insert test record failed

*** Error in `./ex6': corrupted double-linked list: 0x08eadad0 ***

但是如果我删除 for 循环并修改

INSERT INTO test(lat,lng) VALUES (i,20)

INSERT INTO test(lat,lng) VALUES (20,20)  

它可以工作。

Linux Ubuntu 13.04 g++ 编译器

我参考http://www.askyb.com/cpp/c-postgresql-example/

4

2 回答 2

0

问题在于字符串内部没有对“i”进行评估。为了解决这个问题,您可以创建具有正确值的字符串并将其发送到插入命令。

for(int i=0;i<10;i++)
{
    char buffer[256];
    snprintf(buffer, 256, "INSERT INTO test(lat,lng) VALUES (%d,20)", i);
    sSQL.append(buffer);
}

当然,您需要充分调整缓冲区

于 2013-08-28T15:55:48.450 回答
0

问题是您没有发送i. 它看起来像PQexecParams你想要的功能:

PGresult *PQexecParams(PGconn *conn,
                       const char *command,
                       int nParams,
                       const Oid *paramTypes,
                       const char * const *paramValues,
                       const int *paramLengths,
                       const int *paramFormats,
                       int resultFormat);
于 2013-08-28T15:55:59.253 回答