我可以用于循环插入SQL吗?

时间:2013-08-28 15:48:56

标签: c++ sql postgresql insert

#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/

2 个答案:

答案 0 :(得分:0)

问题在于“i”未在字符串内部进行评估。要解决此问题,您可以使用正确的值创建字符串并将其发送到insert命令。

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);
}

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

答案 1 :(得分: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);