首页 > 解决方案 > 如何使用 libpq 库和 C++ 将 NULL 值绑定到准备好的语句?

问题描述

我必须使用 libpq 库而不是 libpqxx,而且我找不到如何在准备好的语句中为数字类型绑定 NULL 值。我尝试了 NULL 或 null 甚至使用 "" 但它没有用。

...
std::string statements = "insert into ipls_troubleticketerrorreport2 (CUSTOMER, NETWORK,SELECTABLEMONTH, ERRORCODE,ERRORMESSAGE, TTID ) " \
                             "values ($1, $2, to_date($3,'DD.MM.YYYY'), $4, $5, $6);";
for (int i=0; i< sqlParametersWithValue.size();i++)
    {
        char NULLstr[] = "NULL";
        if ((sqlParametersWithValue[i].second) == "")
        {
            paramValues[i] = NULLstr;
        }
        else
        {       
            paramValues[i] = &(*(sqlParametersWithValue[i].second).c_str());
        }
    }




pgres =  PQexecParams(pgconn,statements.c_str(), sqlParametersWithValue.size() , NULL, paramValues, NULL, NULL, 0);

标签: c++libpq

解决方案


您正在向它传递一个包含“NULL”的字符串,而不是一个实际的空指针。

paramValues[i] = NULL;
paramValues[i] = nullptr; // If using C++

https://www.postgresql.org/docs/9.1/libpq-exec.html

paramValues[]
指定参数的实际值。该数组中的空指针表示对应的参数为空;否则,指针指向以零结尾的文本字符串(对于文本格式)或服务器预期格式的二进制数据(对于二进制格式)。


推荐阅读