C++ 操作MySql类

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mysql.h" 
#include <iostream>
#include <string>
using namespace std;

class MySQL
{
public:
        MySQL();
        inline BOOL InitSQL(const string&strHost, const string& strUserName, const string& strPwd, const string& strDataBase, const LONG lPort);
        BOOL GetSqlInfo(const string& strSql);
        BOOL DoSql(const string& strSql);
        ~MySQL();

private:
        MYSQL myConnect;
        MYSQL_RES *result;
};

MySQL::MySQL()
{
}

BOOL MySQL::InitSQL(const string&strHost, const string& strUserName, const string& strPwd, const string& strDataBase, const LONG lPort)
{
        mysql_init(&myConnect);
        if (mysql_real_connect(&myConnect, strHost.c_str(), strUserName.c_str(), strPwd.c_str(), strDataBase.c_str(), lPort, NULL, 0)){
                mysql_query(&myConnect, "SET NAMES GBK");
                return TRUE;
        }
        else{
                return FALSE;
        }
}

BOOL MySQL::GetSqlInfo(const string& strSql)
{
        int res = mysql_query(&myConnect, strSql.c_str());
        if(!res){
                result = mysql_store_result(&myConnect);//保存查询到的数据到result
        if(result == NULL){
            return FALSE;
        }
        if(result->row_count > 0){
            int j = mysql_num_fields(result);
            MYSQL_ROW sql_row;
            while (sql_row = mysql_fetch_row(result)){
                for (int i = 0; i < j; i++){
                    printf("%s ", sql_row[i]);
                }
                printf("\n");
            }
            return TRUE;
        }
        else{
            return FALSE;
        }
        }
        else{
                return FALSE;
        }
}

BOOL MySQL::DoSql(const string& strSql)
{
        if (!mysql_query(&myConnect, strSql.c_str())){
                return TRUE;
        }
        else{
                return FALSE;
        }
}

MySQL::~MySQL()
{
        if (result != NULL) mysql_free_result(result);//释放结果资源
        mysql_close(&myConnect);//断开连接
}

int main()
{
        MySQL sql;
        if (sql.InitSQL("localhost", "root", "123456", "test", 3306)){
                sql.GetSqlInfo("select * from test");
                sql.DoSql("insert into test(ID ,username)values(2, '123')");
        }
        else{
                cout << "sql inited failed"<<endl;
        }

        return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。