解决中文在odbc和mysql下乱码问题

1、出现乱码后,要想到字符集设置
2、在odbc配置设置没有作用
3、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应该指向整数值。
4.PHP里Mysql的配置语句:
  mysql_query("set names 'gbk'");//这就是指定数据库字符集,一般放在连接数据库后面就行了,对汉语简体和繁体都可以

举例说明:
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 !\n");
ret = mysql_options(conn, MYSQL_SET_CHARSET_NAME, "gb2312");
    if(ret == 0)
   ;//cout << "mysql_options success!" << endl;
else printf("failed !\n");
if(mysql_real_connect(conn,
       host,
       username,
       password,
       database,
       0, NULL, 0) != NULL)
        ;//cout << "mysql_real_connect success!" << endl;
else printf("failed !\n");

//printf("char set %s\n", mysql_character_set_name(conn));
mysql_query(conn, "insert into teacher values(7, 'fifth', 'shenzhen', '1986-6-6')");
printf("insert affect %d sentences\n", mysql_affected_rows(conn));
if(mysql_query(conn,"SELECT * FROM teacher")) //查询成功返回0    failed here!
   printf("mysql_query failed!\n");
res_set = mysql_store_result(conn);          //失败返回NULL
if(res_set == NULL)
   printf("res_set is null\n");
/*
while((field = mysql_fetch_field(res_set)))
{
   printf("field name %s\n", 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\t\t", field->name);
}
printf("\n");
while ((row = mysql_fetch_row(res_set)) != NULL)
{
   for (i = 0; i < mysql_num_fields(res_set); i ++)
   {
    printf("%s\t\t",row[i] != NULL ? row[i] : "NULL");
   }
   printf("\n");
}
mysql_close(conn);
return 0;
}

你可能感兴趣的:(mysql,PHP,vc++)