jibingp
jibingp

Reputation: 37

how to Insert multiple columns using PQputCopyData

I am trying to insert two columns using PQputCopyData with following code. But once it checks for the final result it shows error invalid byte sequence for encoding UTF8 and data is not getting inserted into the database. Both columns type is character varying. What am I doing wrong here ?

const char *buffer = "john,doe";

PGresult *res;

res=PQexec(conn,"COPY john FROM STDIN DELIMITER ',';");
cout<<buffer;
if(PQresultStatus(res) != PGRES_COPY_IN)
{
    cout<<"copy in not ok";
}
else
{
    if(PQputCopyData(conn,buffer,400) == 1)
    {
        if(PQputCopyEnd(conn,NULL) == 1)
        {
            PGresult *res = PQgetResult(conn);
            if(PQresultStatus(res) == PGRES_COMMAND_OK)
            {

            cout<<"done";
            }
                          else
                           {
            cout<<PQerrorMessage(conn);  Here I get the error invalid  byte sequence for encoding "UTF8"
                            }
        }

        else
        {
            cout<<PQerrorMessage(conn);
        }
    }
}

Upvotes: 0

Views: 1480

Answers (1)

Daniel V&#233;rit&#233;
Daniel V&#233;rit&#233;

Reputation: 61546

   if(PQputCopyData(conn,buffer,400) == 1)

What's wrong is passing 400 instead of the actual size of the contents in buffer, making it send unallocated garbage after the real data. Use strlen(buffer) instead.

Also you want each line to finish with a newline, so buffer should be :

const char *buffer = "john,doe\n";

Upvotes: 1

Related Questions