mysqllibmysqlclientmysql-error

MySQL: Insert special character in a string


I'm using the mysql client c library to insert values into my database. I'm inserting a special character (0xFF) as a separation char in my strings:

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);

This works fine with MySQL 5 (mariadb 5.5.68 on linux) but this doesn't work with MySQL 10 (mariadb 10.5.16 on linux). I get the following error:

error code 1366: Incorrect string value: '\xFFpath...' for column UPSE_Reporting.TestsNameTable.testPath at row 1

Strange is that it works fine if I give the following command in the mysql client with both MySQL 5 and MySQL 10:

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

In both MySQL versions I'm using the same default character set 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)

Any idea why this doesn't work anymore with MySQL 10?


Solution

  • I found the solution myself. I had to set the connection character set to 'latin1'. It seems that the default character set changed from 'latin1' to 'utf8mb4' in version 10. Here is my fix:

    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);
    

    Now the char 255 can be correctly inserted.