如何通过libpq c api插入字节的数组
How to insert array of bytes in PostgreSQL table via libpq C++ API
我正在尝试更新表
CREATE TABLE some_table
(
id integer NOT NULL,
client_fid bigint NOT NULL,
index bytea[],
update_time timestamp without time zone
)
WITH (
OIDS = FALSE
使用从这里剪切的修改代码如何使用libpq?
以二进制格式插入文本数组?#define BYTEAARRAYOID 1001
#define BYTEAOID 17
这是PGVALS_T结构定义
struct pgvals_t
{
/* number of array dimensions */
int32_t ndims;
/* flag describing if array has NULL values */
int32_t hasNull;
/* Oid of data stored in array. In our case is 25 for TEXT */
Oid oidType;
/* Number of elements in array */
int32_t totalLen;
/* Not sure for this one.
I think it describes dimensions of elements in case of arrays storing arrays */
int32_t subDims;
/* Here our data begins */
} __attribute__ ((__packed__));
我已经从struct中删除了数据核指针,因为它影响了备忘录的数据布局
std::size_t nElems = _data.size();
uint32_t valsDataSize = sizeof(prx::pgvals_t) + sizeof(int32_t) * nElems +
sizeof(uint8_t)*nElems;
void *pData = malloc(valsDataSize);
prx::pgvals_t* pvals = (prx::pgvals_t*)pData;
/* our array has one dimension */
pvals->ndims = ntohl(1);
/* our array has no NULL elements */
pvals->hasNull = ntohl(0);
/* type of our elements is bytea */
pvals->oidType = ntohl(BYTEAOID);
/* our array has nElems elements */
pvals->totalLen = ntohl(nElems);
pvals->subDims = ntohl(1);
int32_t elemLen = ntohl(sizeof(uint8_t));
std::size_t offset = sizeof(elemLen) + sizeof(_data[0]);
char * ptr = (char*)(pvals + sizeof(prx::pgvals_t));
for(auto byte : _data){
memcpy(ptr, &elemLen, sizeof(elemLen));
memcpy(ptr + sizeof(elemLen), &byte, sizeof(byte));
ptr += offset;
}
Oid paramTypes[] = { BYTEAARRAYOID };
char * paramValues[] = {(char* )pData};
int paramLengths[] = { (int)valsDataSize };
int paramFormats[] = {1};
PGresult *res = PQexecParams(m_conn, _statement.c_str(),
1,
paramTypes,
paramValues,
paramLengths,
paramFormats,
1
);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::string errMsg = PQresultErrorMessage(res);
PQclear(res);
throw std::runtime_error(errMsg);
}
free(pData);
二进制数据包含在std :: vector变量中,并在a _statement 类型std :: string
中使用以下查询。INSERT INTO some_table
(id, client_id, "index", update_time)
VALUES
(1, 2, $1, NOW())
现在致电pqexecparams后,我有一个例外,带有消息 "绑定参数1中的错误二进制数据格式"
这里有什么问题?
如果要以二进制格式传递bytea[]
,则必须使用array_recv
读取的二进制数组格式,并由array_send
编写。
您不能只通过C数组。
相关文章:
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 基于字节数组生成静态范围整数值
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 swig 追加到字节数组
- C++ 替换字节数组中项的顺序
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 将字节数组转换为多维数组
- 如何将带有空字符的字节数组馈送到 std::iostream 中?
- C++字节数组到整数
- 将字符串转换为无符号字符数组/字节数组
- 用于 progmem 的C++和头文件压缩的 Web 文件字节数组
- 从 UTF-8 字节数组创建字符串?
- 如何将 CString 转换为字节 [] 数组?
- 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- 如何将 (serverClients[i].read() 传递给 ESP8266 上的字节数组
- C++浮点数和字节数组的联合问题
- 如何初始化字节数组的映射?