VC下Mysql 中文乱码问题


1、出现乱码后,要想到字符集设置 
2、VC下Mysql配置语句: 
int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg) 
注意事项: 
(1)能用于设置额外连接选项并且影响一个连接的行为。 
(2)这个函数可以被多次调用来设置多个选项。 
(3mysql_options()应该在mysql_init()之后和mysql_connect()或mysql_real_connect()之前调用。 
(4)option参数是你想要设置的选项;arg参数是选项的值。如果选项是一个整数,那么arg应该指向整数值。

举例说明: 
VC下完整的例子如下: 
#include <iostream> 
#include <windows.h> 
#include <cstdlib> 
#include <cstdio> 
#include <mysql.h> 
#pragma comment(lib, "libmysql.lib") 
using namespace std; 
MYSQL * conn; 
int main() 

char     host[] = "localhost"; 
char username[] = "root"; 
char password[] = "123"; 
    char database[] = "school"; 
MYSQL_RES * res_set; 
MYSQL_ROW row; 
unsigned int i, ret; 
MYSQL_FIELD * field; 
unsigned int num_fields; 
//mysql_init(MYSQL *) 
// return values: An initialized MYSQL* handle. 
//NULL if there was insufficient memory to allocate a new object.     
conn = mysql_init(NULL); 
if(conn != NULL) 
   ;//cout << "mysql_init success!" << endl; 
else printf("failed ! "); 
ret = mysql_options(conn, MYSQL_SET_CHARSET_NAME, "gb2312"); 
    if(ret == 0) 
   ;//cout << "mysql_options success!" << endl; 
else printf("failed ! "); 
if(mysql_real_connect(conn, 
       host, 
       username, 
       password, 
       database, 
       0, NULL, 0) != NULL) 
        ;//cout << "mysql_real_connect success!" << endl; 
else printf("failed ! "); 

//printf("char set %s ", mysql_character_set_name(conn)); 
mysql_query(conn, "insert into teacher values(7, 'fifth', 'shenzhen', '1986-6-6')"); 
printf("insert affect %d sentences ", mysql_affected_rows(conn)); 
if(mysql_query(conn,"SELECT * FROM teacher")) //查询成功返回0    failed here! 
   printf("mysql_query failed! "); 
res_set = mysql_store_result(conn);          //失败返回NULL 
if(res_set == NULL) 
   printf("res_set is null "); 
/* 
while((field = mysql_fetch_field(res_set))) 

   printf("field name %s ", field->name); 

*/ 
num_fields = mysql_num_fields(res_set); 
for(i = 0; i < num_fields; i++) 

   field = mysql_fetch_field_direct(res_set, i); 
   printf("%s ", field->name); 

printf(" "); 
while ((row = mysql_fetch_row(res_set)) != NULL) 

   for (i = 0; i < mysql_num_fields(res_set); i ++) 
   { 
    printf("%s ",row[i] != NULL ? row[i] : "NULL"); 
   } 
   printf(" "); 

mysql_close(conn); 
return 0; 

原文地址:https://www.cnblogs.com/hzcya1995/p/13318797.html