[英]PostgreSQL C++ libpq encoding UTF-8 problem
I don't have problem inserting UTF-8 (korean character in my case) using direct sql command in PGAdmin or psql console.我在 PGAdmin 或 psql 控制台中使用直接 sql 命令插入 UTF-8 (在我的情况下为韩语字符)没有问题。 But when I need to insert values in C++ by using libpq library, I got the encoding error and I couldn't resolve it until now.但是当我需要使用 libpq 库在 C++ 中插入值时,我得到了编码错误,直到现在我才能解决它。
I have tested DB connection, etc and works well.我已经测试了数据库连接等并且运行良好。 So I will just share the insertion code only:所以我只会分享插入代码:
/* INSERT demo */
res = PQexec(conn,
"insert into db_test values('testval', '군포지사','N00225','영동선','0500','E',13.67,14.18);");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "Insert into table failed: " << PQresultErrorMessage(res)
<< std::endl;
}
else
std::cout << "inserted" << std::endl;
PQclear(res);
Below is the error:以下是错误:
Insert into table failed: ERROR: invalid byte sequence for encoding "UTF8": 0xb1
I have managed to solve it, sorry for my lack of understanding in encoding processing.我已经设法解决了,抱歉我对编码处理缺乏了解。 I just need to convert ANSI to UTF-8, below is my working code.我只需要将 ANSI 转换为 UTF-8,下面是我的工作代码。 If there's a better solution, please post your answer.如果有更好的解决方案,请发布您的答案。
int AnsiToUTF8(char* szSrc, char* strDest, int destSize)
{
WCHAR szUnicode[255];
char szUTF8code[255];
int nUnicodeSize = MultiByteToWideChar(CP_ACP, 0, szSrc, (int)strlen(szSrc), szUnicode, sizeof(szUnicode));
int nUTF8codeSize = WideCharToMultiByte(CP_UTF8, 0, szUnicode, nUnicodeSize, szUTF8code, sizeof(szUTF8code), NULL, NULL);
assert(destSize > nUTF8codeSize);
memcpy(strDest, szUTF8code, nUTF8codeSize);
strDest[nUTF8codeSize] = 0;
return nUTF8codeSize;
}
/* INSERT demo */
char queryUtf8[100];
std::string queryAnsi = "insert into db_test values('testval', '군포지사','N00225','영동선','0500','E',13.67,14.18);";
AnsiToUTF8(&queryAnsi[0u], queryUtf8, 100);
res = PQexec(conn, queryUtf8);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
std::cout << "Insert into table failed: " << PQresultErrorMessage(res)
<< std::endl;
}
else
std::cout << "inserted" << std::endl;
PQclear(res);
The proper solution is to set the client_encoding
parameter to the correct value (the encoding your client uses).正确的解决方案是将client_encoding
参数设置为正确的值(您的客户端使用的编码)。 You can do that when connecting to the database:您可以在连接到数据库时执行此操作:
PGconn *conn;
conn = PQconnectdb("user=carl password=secret client_encoding=LATIN1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.