在编写接口API时,发现中文字utf8输入的在linux下采用c读取显示为”??”问号,这是由于编码造成的。很简单的两个地方做修改就搞定。
1.先找到mysql的f配置文件/etc/f编辑添加
[mysqld]
default-character-set=utf8
2.在程序中添加 mysql_set_character_set(&db,”utf8″); 语句
例子:kiccleaf.c 文件
#include
//这里需要找到相应地址不知道可以用“ find / -name mysql.h ”查询
#include "/usr/include/mysql/mysql.h"
int main()
{
MYSQL db;/*connector*/
MYSQL_RES* result;/*result buffer*/
MYSQL_ROW row;/*one row of the result*/
int i;
if(mysql_init(&db) ==NULL)
{
fprintf(stderr,"Fail to initialize the db.\n");
return -1;
}
if(!mysql_real_connect(&db,"localhost","root","password","kiccleaf",3306,NULL,0))
{
fprintf(stderr,"Fail to connect to the server");
return -1;
}
//添加字符集防止乱码
mysql_set_character_set(&db,"utf8");
if(mysql_query(&db,"SELECT * FROM user") != 0)
{
fprintf(stderr,"Fail to query the db for information.\n");
return -1;
}
if ((result = mysql_store_result(&db)) == NULL)
{
fprintf(stderr,"Fail to get the result.\n");
return -1;
}
while((row=mysql_fetch_row(result)) != NULL)/*fetching each row*/
{
puts("================================================");
printf("id: %s\n",row[0]);
printf("name: %s\n",row[1]);
printf("pwd: %s\n",row[2]);
printf("flag: %s\n",row[3]);
puts("================================================");
}
mysql_free_result(result);
mysql_close(&db);
return 0;
}
编译时也会出现问题,可以添加参数 “-lz /usr/lib/mysql/libmysqlclient.so.15.0.0”
gcc -o kiccleaf -g kiccleaf.c -lz /usr/lib/mysql/libmysqlclient.so.15.0.0
原来乱码的情况
[root@kiccleaf c]# ./kiccleaf
================================================
id: 0000000001
name: ???
pwd: 123456
flag: 0
================================================
================================================
id: 0000000002
name: ???
pwd: 654123
flag: 0
================================================
================================================
id: 0000000003
name: ???
pwd: 789456
flag: 0
================================================
================================================
id: 0000000004
name: ???
pwd: 456321
flag: 0
================================================
添加字符集后输出结果:
[root@kiccleaf c]# ./kiccleaf
================================================
id: 0000000001
name: 测试1
pwd: 123456
flag: 0
================================================
================================================
id: 0000000002
name: 测试2
pwd: 654123
flag: 0
================================================
================================================
id: 0000000003
name: 测试3
pwd: 789456
flag: 0
================================================
================================================
id: 0000000004
name: 测试4
pwd: 456321
flag: 0
================================================
如果觉得《c mysql中文乱码解决方案_Linux下c读取MysqL中文乱码解决方案》对你有帮助,请点赞、收藏,并留下你的观点哦!