C++連接MYSQL數據庫

openkk 13年前發布 | 54K 次閱讀 C/C++開發 C/C++

一個實現C/C++連接MYSQL數據庫的很好的例子
//下面的代碼是一個實現C++連接MYSQL數據庫的很好的例子
//這里用了建表,插入,檢索,刪表等常用功能
//我用VC++6.0生成,已經成功連接了。
//在VC++6.0中要想把做一下兩步準備工作才可以。
//(1)Tools->Options->Directories->Include files中添加C:\Program Files\MySQL\MySQL Server 6.0\include
//(2)Tools->Options->Directories->Library files中添加C:\Program Files\MySQL\MySQL Server 6.0\lib\opt
//其實就是將頭文件和庫文件包含進來
//我覺得這個例子寫的很好,再結合自己的試驗,特地介紹給大家!

#include <winsock.h>
#include <iostream>
#include <string>
#include <mysql.h>
using namespace std;

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libmysql.lib")

//單步執行,不想單步執行就注釋掉
#define STEPBYSTEP

int main() {
    cout << "****************************************" << endl;

#ifdef STEPBYSTEP
    system("pause");
#endif

    //必備的一個數據結構
    MYSQL mydata;

    //初始化數據庫
    if (0 == mysql_library_init(0, NULL, NULL)) {
        cout << "mysql_library_init() succeed" << endl;
    } else {
        cout << "mysql_library_init() failed" << endl;
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //初始化數據結構
    if (NULL != mysql_init(&mydata)) {
        cout << "mysql_init() succeed" << endl;
    } else {
        cout << "mysql_init() failed" << endl;
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //在連接數據庫之前,設置額外的連接選項
    //可以設置的選項很多,這里設置字符集,否則無法處理中文
    if (0 == mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk")) {
        cout << "mysql_options() succeed" << endl;
    } else {
        cout << "mysql_options() failed" << endl;
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //連接數據庫
    if (NULL
            != mysql_real_connect(&mydata, "localhost", "root", "test", "test",
                    3306, NULL, 0))
            //這里的地址,用戶名,密碼,端口可以根據自己本地的情況更改
            {
        cout << "mysql_real_connect() succeed" << endl;
    } else {
        cout << "mysql_real_connect() failed" << endl;
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //sql字符串
    string sqlstr;

    //創建一個表
    sqlstr = "CREATE TABLE IF NOT EXISTS user_info";
    sqlstr += "(";
    sqlstr +=
            "user_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique User ID',";
    sqlstr +=
            "user_name VARCHAR(100) CHARACTER SET gb2312 COLLATE gb2312_chinese_ci NULL COMMENT 'Name Of User',";
    sqlstr +=
            "user_second_sum INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'The Summation Of Using Time'";
    sqlstr += ");";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() create table succeed" << endl;
    } else {
        cout << "mysql_query() create table failed" << endl;
        mysql_close(&mydata);
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //向表中插入數據
    sqlstr =
            "INSERT INTO user_info(user_name) VALUES('公司名稱'),('一級部門'),('二級部門'),('開發小組'),('姓名');";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() insert data succeed" << endl;
    } else {
        cout << "mysql_query() insert data failed" << endl;
        mysql_close(&mydata);
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //顯示剛才插入的數據
    sqlstr = "SELECT user_id,user_name,user_second_sum FROM user_info";
    MYSQL_RES *result = NULL;
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() select data succeed" << endl;

        //一次性取得數據集
        result = mysql_store_result(&mydata);
        //取得并打印行數
        int rowcount = mysql_num_rows(result);
        cout << "row count: " << rowcount << endl;

        //取得并打印各字段的名稱
        unsigned int fieldcount = mysql_num_fields(result);
        MYSQL_FIELD *field = NULL;
        for (unsigned int i = 0; i < fieldcount; i++) {
            field = mysql_fetch_field_direct(result, i);
            cout << field->name << "\t\t";
        }
        cout << endl;

        //打印各行
        MYSQL_ROW row = NULL;
        row = mysql_fetch_row(result);
        while (NULL != row) {
            for (int i = 0; i < fieldcount; i++) {
                cout << row[i] << "\t\t";
            }
            cout << endl;
            row = mysql_fetch_row(result);
        }

    } else {
        cout << "mysql_query() select data failed" << endl;
        mysql_close(&mydata);
        return -1;
    }

#ifdef STEPBYSTEP
    system("pause");
#endif

    //刪除剛才建的表
    sqlstr = "DROP TABLE user_info";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() drop table succeed" << endl;
    } else {
        cout << "mysql_query() drop table failed" << endl;
        mysql_close(&mydata);
        return -1;
    }
    mysql_free_result(result);
    mysql_close(&mydata);
    mysql_server_end();

    system("pause");
    return 0;
}

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!