linux 下C++連接mysql數據庫

想在程序中加入存儲數據的功能,程序使用C++語言開發,於是就打算看看C++如何訪問MySql,之前自學過MySql,也安裝過MySql的開發包,相應的頭文件已經有了,看了一下mysql.h頭文件,裏面有C的API,所以就需要用C++來封裝一下,借鑑一下網上已有的資源,下面列出封裝後的程序:

MySqlDb.h

#ifndef MYSQLDB_H
#define MYSQLDB_H
#include <mysql/mysql.h>
#include <string>
using namespace std;
class MySqlDb
{
public:
    MySqlDb();
    bool initDB(string server_host , string user, string password, string db_name);
    bool executeSQL(string sql_str);
    bool create_table(string table_str_sql);
    ~MySqlDb();
private:
    MYSQL *connection;
    MYSQL_RES *res;
    MYSQL_ROW row;
};
#endif

MySqlDb.cpp

#include "MySqlDb.h"
#include <stdlib.h>
#include <iostream>
MySqlDb::MySqlDb()
{  
    //init mysql connection
    connection = mysql_init(NULL);
    if(connection == NULL)
    {
        cout<<"mysql_init error\n";
        exit(1);
    }
}
MySqlDb::~MySqlDb()
{  
    //shutdown connect
    if(connection != NULL)
    {
        mysql_close(connection);
    }
}
//
bool MySqlDb::initDB(string server_host , string user, string password , string db_name )
{  
    //implement connect to mysql
    connection = mysql_real_connect(connection , server_host.c_str() , user.c_str() , password.c_str() , db_name.c_str() , 0 , NULL , 0);
    if(connection == NULL)
    {
        cout<<"mysql_real_connect error\n";
        exit(1);
    }
    return true;
}
//execute mysql
bool MySqlDb::executeSQL(string sql_str)
{
    // query
    if(mysql_query(connection, "set names utf8"))
    {
        cout<<mysql_errno(connection)<<" "<<mysql_error(connection)<<"\n";
    }
    int t = mysql_query(connection,  sql_str.c_str());
    if(t)
    {
        cout<<"Error making query: "<<mysql_error(connection)<<"\n";
        exit(1);
    }
    else
    { 
        res = mysql_use_result(connection);
        if(res)
        {
            for(int i = 0 ; i < mysql_field_count(connection) ; i++)
            {  
                row = mysql_fetch_row(res);    
                if(row <= 0)
                     {
                    break;
                 }
                 for(int r = 0 ; r  < mysql_num_fields(res) ; r ++)
                    {
                     cout<<row[r]<<" ";   
                    }
                cout<<"\n";
            }
        }
       mysql_free_result(res);
    }
    return true;
}
//create table
bool MySqlDb::create_table(string table_str_sql)
{
    int t = mysql_query(connection , table_str_sql.c_str());
    if(t)
    {
        cout<<"Error making query: "<<mysql_error(connection)<<"\n";
        exit(1);
    }
    return true;
}

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