最近用C语言连接数据库,插入数据时如果数据中存在汉字,插入会失败。最后搞明白了是MySQL使用的字符集的问题。
1、如何查看当前连接的数据库使用的字符集
MySQL提供的接口函数prototype为:
void STDCALL mysql_get_character_set_info(MYSQL *mysql,
MY_CHARSET_INFO *charset);
其中 MY_CHARSET_INFO 结构体定义如下:
typedef struct character_set { unsigned int number; /* character set number */ unsigned int state; /* character set state */ const char *csname; /* collation name */ const char *name; /* character set name */ const char *comment; /* comment */ const char *dir; /* character set directory */ unsigned int mbminlen; /* min. length for multibyte strings */ unsigned int mbmaxlen; /* max. length for multibyte strings */ } MY_CHARSET_INFO;
调用上述函数并打印结果:
MY_CHARSET_INFO charset; mysql_get_character_set_info(mysql, &charset); printf("character set number:%d\n", charset.number); printf("character set state:%d\n", charset.state); printf("collation name:%s\n", charset.csname); printf("character set name:%s\n", charset.name); printf("comment:%s\n", charset.comment); printf("character set directory:%s\n", charset.dir); printf("min. length for multibyte strings:%d\n", charset.mbminlen); printf("max. length for multibyte strings:%d\n", charset.mbmaxlen);
结果如下:
可以看出当前数据库使用的字符集为latin1。现在还不知道为什么插入汉字会提示出错,虽然客户端、连接、数据库三个方面使用的字符集都是latin1,按理说latin1使用了字节的所有8位空间,不管什么字节流过来都不会报错。
2、如何修改当前连接使用的字符集
MySQL提供的接口函数prototype为:
int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname);
成功返回0,失败返回非0。
在网上查资料有人说使用"utf8",我试了一下,发现还是不行。使用“GBK”可以:
if (!mysql_set_character_set(mysql, "GBK")) { printf("New connection character set: %s\n", mysql_character_set_name(mysql)); }
其字符集信息如下:
The End.