C/C ++: mysql Character Set setting
In Linux, when we use mysql c api to operate on mysqldb, by default, the program will perform SQL operations using the Latin1 character set. In this case, garbled characters may occur,
For example, the character set in the database is utf8, And then we insert a record into it through the program, and then when we query it, garbled characters will appear.
To solve this problem, we can call the int mysql_set_character_set (MYSQL * mysql, const char * csname) function to set the corresponding character set for each connection to mysql. For example, the following code:
MYSQL mysql; mysql_init(&mysql); if (!mysql_real_connect(&mysql, "host" , "user" , "passwd" , "database" ,0,NULL,0)) { fprintf (stderr, "Failed to connect to database: Error: %s\n" , mysql_error(&mysql)); } if (!mysql_set_character_set(&mysql, "utf8" )) { printf ( "New client character set: %s\n" , mysql_character_set_name(&mysql)); } |
Sometimes, when we perform SQL operations directly on the mysql client, in order to solve the garbled problem, we generally execute: set names *** before executing an SQL statement ***,
This functionMysql_set_character_set () is the same as set names.