我正在使用 libmysqlclient 编写 C 程序以将数据(令人惊讶地)插入数据库。代码插入的表的字符集及其排序规则是:
CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
在我的 C 程序中,我使用 mysql_set_character_set()
来更改字符集;问题是这个函数只改变字符集而不是排序规则。如果我使用 mysql_get_character_set_info
查询字符集和排序规则,结果是:
char-set=utf8mb4, collation=utf8mb4_general_ci
根据 MySQL documentation :
SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client.
所以我决定使用 mysql_options
和 MYSQL_INIT_COMMAND
更改连接排序规则:
SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';
生成的函数调用如下所示(我在 mysql_real_connect()
之前调用了它):
if(mysql_options(conn, MYSQL_INIT_COMMAND,
"SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';")) {
// log the errors and do proper actions
}
但是这个命令似乎不能改变字符集和排序规则!因为现在如果我使用 mysql_get_character_set_info()
查询字符集,结果是:
char-set=latin1, collation=latin1_swedish_ci
这里有趣的是,在 MySQL 端,如果我启用日志并使用 MYSQL_INIT_COMMAND
命令执行程序!但是 mysql_get_character_set_info()
没有显示这个!再次根据 libmysql 的文档:
int mysql_set_character_set(MYSQL *mysql, const char *csname)
This function is used to set the default character set for the current connection. The string csname specifies a valid character set name. The connection collation becomes the default collation of the character set. This function works like the SET NAMES statement, but also sets the value of mysql->charset, and thus affects the character set used by mysql_real_escape_string()
我想以 mysql_real_escape_string()
受到影响的方式更改字符集和排序规则。正确的做法是什么?
最佳答案
root
用户不执行 init 命令。 (更具体地说,任何 SUPER
用户。)建议您为您的应用程序创建一个不同的用户。
不要忘记您的表列也应声明为CHARACTER SET utf8mb4
。
关于mysql - 使用 libmysqlclient C API 设置 collation_connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39446292/