Search code examples
sqlcdatabasepostgresqllibpq

How handle UTF-8 encoding error in libpq?


I have created this function to insert data into database:

void add_data_to_db(){
        const char *data[2][2] = {"2","e"};
        re = PQexecParams(connection,
                        "INSERT INTO test_table "\
                        "VALUES ($1, $2);",
                        2,NULL,data[2],NULL,NULL,0);
        if(PQresultStatus(re) != PGRES_TUPLES_OK){
                printf("%s\n", PQresultErrorMessage(re));
        }

        PQclear(re);
}

but when I run the program it prints :

ERROR:  invalid byte sequence for encoding "UTF8": 0x80

as far as I know this problem occurs when we have null value adding to table but I have not.


Solution

  • It should be const char *data[2], and the function call should have data rather than data[2].

    The error message means that PostgreSQL encountered bytes that are not part of a correctly encoded UTF-8 string.