进入带有 bytea 属性的 postgresql 表,没有 UTF8 编码错误?,c++,postgresql,stringstream,libpqxx"/>

首页 > 解决方案 > 有没有办法插入矢量进入带有 bytea 属性的 postgresql 表,没有 UTF8 编码错误?

问题描述

ERROR: invalid byte sequence for encoding "UTF8": 0xe0 0x20 0x63当我尝试将 std::vector 的 sql 语句(插入)执行到 bytea 中时,我得到了。

我正在使用c++ (11), and pqxx postgresql client, and posgresql 9.6. 我需要将字节流(向量)写入 db。

很多时候我的代码运行良好,但现在我遇到了以下错误:

错误:编码“UTF8”的字节序列无效:0xe0 0x20 0x63

从 pgAdmin4 我得到:

显示客户端编码;-> 统一码

在 c++ 中,我使用以下代码从 std::stringstream 填充此向量:

//mOutputStream is std::stringstream correctly filled
mOutputStream.seekg(0, std::ios::end);
int sizeOS = mOutputStream.tellg();
mOutputStream.seekg(0, std::ios::beg);
mOutputStream.unsetf(std::ios::skipws);

std::streampos vecSize;
mOutputStream.seekg(0, std::ios::end);
vecSize = mOutputStream.tellg();
mOutputStream.seekg(0, std::ios::beg);

//std::vector<unsigned char>& arrayChar
arrayChar.reserve(vecSize);

arrayChar.insert(arrayChar.begin(),                  

std::istream_iterator<unsigned char>(mOutputStream),
std::istream_iterator<unsigned char>());

然后,使用 pqxx 库,我创建一个 sql 语句:

sql = "Insert into public.\"MyFile\" (id,rawdata) values ($1,$2);";
/* Create a transactional object. */
pqxx::work W(C);
C.prepare("InsertRaw", sql);
...
void * bin_data = static_cast<void*>(arrayChar.data());  
size_t bin_size = arrayChar.size(); // ...and the size of the binary data

pqxx::binarystring blob(bin_data, bin_size);
//at this line i get the error of UTF8 encoding
pqxx::result r = W.prepared("InsertRaw")(idFile.c_str())(blob).exec();

W.commit();
C.disconnect();

这是我得到的错误:

错误:编码“UTF8”的字节序列无效:0xe0 0x20 0x63

标签: c++postgresqlstringstreamlibpqxx

解决方案


pqxx::binarystring用于您从服务器读取的 bytea 数据。

对于提交二进制数据,文档说:

要转换另一种方式,即从原始字节序列转换为适合作为字节值包含在 SQL 中的字符串,请使用事务的 esc_raw() 函数。


推荐阅读