c++ - 有没有办法插入矢量进入带有 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
解决方案
pqxx::binarystring
用于您从服务器读取的 bytea 数据。
对于提交二进制数据,文档说:
要转换另一种方式,即从原始字节序列转换为适合作为字节值包含在 SQL 中的字符串,请使用事务的 esc_raw() 函数。
推荐阅读
- python - 如何在 keras 中加载预训练的词嵌入并输出不同的类
- typescript - 如何从 Vuetify 数据表组件的类中获取数据?
- python - 如何到达 QTreeWidget 第二列 QComboBox 中的内容?
- pascal - 在 Pascal 中使用 MOD
- r - 如何在 R 中添加表格或矩阵的总和行?
- c# - 使用数组显示数据库中的多个图像
- javascript - 隐藏水平滚动条,但保持滚动功能
- docker - Kubernetes中的Accumulo集群部署
- php - 在发布到服务器之前使用 php 验证 json 数组中是否存在条目
- angular - 使用 routerLink 角度 6-7 时组件没有获取 contentChildren