C++調用MySQL實例

#include <mysql/mysql.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

using namespace std;

int main(){
    MYSQL _sql;
    mysql_init(&_sql);
    if(!mysql_real_connect(&_sql, "localhost", "root", "123", "shiyao", 0, NULL, 0)){
        cout<<"not connected!!"<<endl;
        cout<<mysql_error(&_sql)<<endl;
    }
    else{
        cout<<"connected!!"<<endl;
    }

    //get the result from the executing select query
    char *query = "SELECT * FROM test1";

    int t = mysql_real_query(&_sql, query, (unsigned int)strlen(query));
    if(t){
        cout<<"Error making query:"<<mysql_error(&_sql);
    }

    MYSQL_RES* res = mysql_store_result(&_sql);
    if(!res){
        cout<<"res failed!"<<endl;
    }
    MYSQL_ROW row;
    while (row = mysql_fetch_row(res)){
        for(t = 0; t < mysql_num_fields(res); t++){
            cout<<row[t];
        }
        cout<<endl;
    }

    //free result after you get the result
    mysql_free_result(res);

    sleep(1);

    mysql_close(&_sql);



    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章