MySQL:在字符串中插入特殊字符

mwg9r5ms  于 2023-01-08  发布在  Mysql
关注(0)|答案(1)|浏览(338)

我正在使用mysql客户端c库向数据库中插入值,并在字符串中插入一个特殊字符(0xFF)作为分隔符:

char buffer[256];
char name[64] = "my_name";
char path[64] = "path/path";

path[4] = 255;      // replace / with 0xFF

sprintf(buffer, "INSERT TestsNameTable (testName, testPath) VALUES (\"%s\", \"%s\")", name, path);
mysql_query(&mSQLConnection, buffer);

这在MySQL 5(mariadb 5.5.68在linux上)上运行良好,但在MySQL 10(mariadb 10.5.16在linux上)上不运行。
错误代码1366:字符串值不正确:第1行上UPSE_Reporting列的"\xFF路径..."。TestsNameTable列的"\xFF路径..."
奇怪的是,如果我在MySQL 5和MySQL 10的mysql客户端中给出以下命令,它工作正常:

MariaDB [UPSE_Reporting]> INSERT INTO TestsNameTable (testName, testPath) VALUES ("cedric", CONCAT("path",CHAR(255),"path"));
Query OK, 1 row affected (0.02 sec)

在两个MySQL版本中,我使用相同的默认字符集latin1:

MariaDB [UPSE_Reporting]> SELECT table_schema, table_name, column_name, character_set_name, collation_name FROM information_schema.columns WHERE table_schema="UPSE_Reporting" AND table_name="TestsNameTable" ORDER BY table_schema, table_name,ordinal_position; 

+----------------+----------------+-------------+--------------------+-------------------+
| table_schema   | table_name     | column_name | character_set_name | collation_name    |
+----------------+----------------+-------------+--------------------+-------------------+
| UPSE_Reporting | TestsNameTable | _rowid      | NULL               | NULL              |
| UPSE_Reporting | TestsNameTable | testName    | latin1             | latin1_swedish_ci |
| UPSE_Reporting | TestsNameTable | testPath    | latin1             | latin1_swedish_ci |
+----------------+----------------+-------------+--------------------+-------------------+
3 rows in set (0.00 sec)

你知道为什么MySQL 10不再支持这个功能吗?

mum43rcc

mum43rcc1#

我自己找到了解决方案。我不得不将连接字符集设置为“latin1”。在版本10中,默认字符集似乎从“latin1”更改为“utf8mb4”。以下是我的修复方法:

char buffer[256];
char name[64] = "my_name";
char path[64] = "path/path";

path[4] = 255;      // replace / with 0xFF

mysql_init(&mSQLConnection);
mysql_real_connect(&mSQLConnection, database, user, password, "UPSE_Reporting", 0, NULL, 0);
mysql_set_character_set(&mSQLConnection, "latin1");
sprintf(buffer, "INSERT TestsNameTable (testName, testPath) VALUES (\"%s\", \"%s\")", name, path);
mysql_query(&mSQLConnection, buffer);

现在可以正确地插入char 255。

相关问题