C语言接口查询Mysql数据库,中文显示?

解决方法:在查询语句前加入如下代码,有两种方式:

1)

            if (!mysql_set_character_set(&conn, "utf8"))
            {
                printf("New client character set: %s\n", mysql_character_set_name(&conn));
            }
            printf("%s\n","设置字符格式为中文" );

2)

 mysql_query(&conn, "SET NAMES utf8;");

完整代码如下:

#ifndef __LCC__
#define __LCC__
#endif

#include 
#include 
#include "mysql.h"

int main(int argc, char **argv) {
    MYSQL mysql_conn; /* Connection handle */
    MYSQL_RES *mysql_result; /* Result handle */
    MYSQL_ROW mysql_row; /* Row data */
    int f1, f2, num_row, num_col;
    if (!mysql_set_character_set(&mysql_conn, "utf8"))
    {
        printf("New client character set: %s\n", mysql_character_set_name(&mysql_conn));
    }
    if (mysql_init(&mysql_conn) != NULL) {
        if (mysql_real_connect(
                               &mysql_conn, "localhost", "root",
                               "密码", "数据库名称", MYSQL_PORT, NULL, 0) != NULL){
//            char *sql="set names utf8;";
//            mysql_query(&mysql_conn,sql);
            if (mysql_query(
                            &mysql_conn,
                            "select * from EMPLOYEE limit 10") == 0) {
                mysql_result = mysql_store_result(&mysql_conn);
                num_row = mysql_num_rows(mysql_result);
                num_col = mysql_num_fields(mysql_result);

                for (f1 = 0; f1 < num_row; f1++) {
                    mysql_row = mysql_fetch_row(mysql_result);

                    for (f2 = 0; f2 < num_col; f2++)
                        printf(
                               "[Row %d, Col %d] ==> [%s]\n",
                               f1+1, f2+1, mysql_row[f2]);
                }
            } else
                printf("Query fails\n");
        } else {
            int i = mysql_errno(&mysql_conn);
            //const *s = mysql_error(&mysql_conn);
            //printf("Connection fails(ERROR %d): %s\n", i, s);
        }
    } else
        printf("Initialization fails\n");

    mysql_free_result(mysql_result);
    mysql_close(&mysql_conn);
    return 0;
}

 

参考博客:

https://blog.csdn.net/qq_28508217/article/details/70827391?biz_id=102&utm_term=mysql_use_result%E6%9F%A5%E8%AF%A2%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%AD%E7%9A%84%E4%B8%AD%E6%96%87%E6%98%AF%E4%B9%B1%E7%A0%81&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-70827391&spm=1018.2118.3001.4187

你可能感兴趣的:(数据库,C++)