Mysql C/C++开发教程

Mysql C/C++开发教程

点击进入Mysql C/C++开发视频课程

代码示例

// testmysqlib.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <mysql.h>
#include <thread>
using namespace std;
int main()
{
    //初始化mysql上下文
    MYSQL mysql;
    //单线程模式 mysql_init自动调用 mysql_library_init 线程不安全
    mysql_init(&mysql);
    const char *host = "127.0.0.1";
    //const char *host = "192.168.0.203";
    const char *user = "root";
    const char *pass = "123456";
    const char *db = "mysql";       //数据库名称
    if (!mysql_real_connect(&mysql,host, user, pass, db, 3306, 0, 0))
    {
        cout << "mysql connect failed!" << mysql_error(&mysql) << endl;
    }
    else
    {
        cout << "mysql connect success!" << endl;
    }

    //user select * from user
    // 1 执行SQL语句
    const char *sql = "select * from user";
    // mysql_real_query  sql语句中可以包含二进制数据
    // mysql_query sql语句中只能是字符串
    // 0返回表示成功 
    int re = mysql_real_query(&mysql, sql, strlen(sql));

    // Commands out of sync; you can't run this command now 
    // 执行sql语句后,必须获取结果集并且清理
    // re = mysql_query(&mysql, sql);
    if (re != 0)
    {
        cout << "mysql_real_query faied! "<< sql<<" " << mysql_error(&mysql) << endl;
    }
    else
    {
        cout << "mysql_real_query success! " << sql << endl;
    }


    //2 获取结果集

    // mysql_use_result 不实际读取数据
    //MYSQL_RES* result = mysql_use_result(&mysql);
    //mysql_store_result 读取所有数据,注意缓存大小 MYSQL_OPT_MAX_ALLOWED_PACKET 默认 64M
    MYSQL_RES* result = mysql_store_result(&mysql);
    if (!result)
    {
        cout << "mysql_use_result faied! "  << mysql_error(&mysql) << endl;
    }

    //获取表字段
    MYSQL_FIELD *field = 0;
    while (field = mysql_fetch_field(result))
    {
        cout << "key:" << field->name << endl;
    }

    //获取表字段数量
    int fnum = mysql_num_fields(result);




    //3 遍历结果集
    MYSQL_ROW row;
    while (row = mysql_fetch_row(result))
    {
        unsigned long * lens = mysql_fetch_lengths(result);

        //cout<< lens[0] << "[" << row[0] << "," << row[1] << "]" << endl;
        for (int i = 0; i < fnum; i++)
        {
            cout << mysql_fetch_field_direct(result, i)->name << ":";
            if (row[i])
                cout << row[i];
            else
                cout << "NULL";
            cout<< ",";
        }
        cout <<"\n=========================================="<< endl;

    }

    //清理结果集
    mysql_free_result(result);



    mysql_close(&mysql);
    mysql_library_end();
    std::cout << "Hello World!\n";
    getchar();
}

关闭