MySQL的C++封裝

jopen 10年前發布 | 71K 次閱讀 MySQL 數據庫服務器

直接在MySQL的C語言的API上以面向對象的方式封裝實現了數據庫的創建,表的創建,數據庫的讀寫操作快速搭建原型,目前沒有添加連接池模塊和事務處理。

1.MySQL的特性

使用C和C++編寫,并使用了多種編譯器進行測試,保證源代碼的可移植性。
支持AIX、BSDi、FreeBSD、HP-UX、Linux、Mac OS、Novell NetWare、NetBSD、OpenBSD、OS/2 Wrap、Solaris、Windows等多種操作系統。
為多種編程語言提供了API。這些編程語言包括C、C++、C#、VB.NET、Delphi、Eiffel、Java、Perl、PHP、Python、Ruby和Tcl等。
支持多線程,充分利用CPU資源,支持多用戶。
優化的SQL查詢算法,有效地提高查詢速度。
既能夠作為一個單獨的應用程序在客戶端服務器網絡環境中運行,也能夠作為一個程序庫而嵌入到其他的軟件中。
提供多語言支持,常見的編碼如中文的GB 2312、BIG5,日文的Shift JIS等都可以用作數據表名和數據列名。
提供TCP/IP、ODBC和JDBC等多種數據庫連接途徑。
提供用于管理、檢查、優化數據庫操作的管理工具。
可以處理擁有上千萬條記錄的大型數據庫。

2.C++的API封裝

用C++連接SQL有兩種可直接使用的接口:MySQL Connector/C++和MySQL+ +,<1>MySQL Connector/C++是最新發布的MySQL連接器,由Sun Microsystems開發。MySQL connector為C++提供面向對象的編程接口(API)和連接MySQL Server的數據庫驅動器與現存的driver不同,Connector/C++是JDBC API在C++中的實現。換句話說,Connector/C++ driver的接口主要是基于Java語言的JDBC API。Java數據庫連接(JDBC)是Java連接各種數據庫的業界標準。Connector/C++實現了JDBC 4.0的大部分規范。熟悉JDBC編程的C++程序開發者可以提高程序開發的效率。

<2>MySQL++是一個用C++封裝了MySQL的C API的類庫。它是建立標準C ++標準庫(STL)之上,使處理數據庫處理STL容器一樣容易。此外,MySQL的++提供了讓你避免最重復的工作,提供了原生C++接口。

3.MySQL的C++封裝實現

在快速搭建原型的過程中,沒有用到這兩種連接方式,直接在MySQL C API上封裝實現。

    #ifndef __MYSQL_INTERFACE_H__  
    #define __MYSQL_INTERFACE_H__  

    #include "winsock.h"  
    #include <iostream>  
    #include <string>  
    #include "mysql.h"  
    #include <vector>  
    #include <string>  

    #pragma comment(lib, "ws2_32.lib")  
    #pragma comment(lib, "libmysql.lib")  
    using namespace std;  

    class MySQLInterface  
    {  
    public:    
        MySQLInterface();  
        virtual ~MySQLInterface();  

        bool connectMySQL(char* server, char* username, char* password, char* database,int port);  
        bool createDatabase(std::string& dbname);  
        bool createdbTable(const std::string& query);  

        void errorIntoMySQL();  
        bool writeDataToDB(string queryStr);  
        bool getDatafromDB(string queryStr, std::vector<std::vector<std::string> >& data);  
        void closeMySQL();  

    public:  
        int errorNum;                    //錯誤代號  
        const char* errorInfo;             //錯誤提示  

    private:  
        MYSQL mysqlInstance;                      //MySQL對象,必備的一個數據結構  
        MYSQL_RES *result;                 //用于存放結果 建議用char* 數組將此結果轉存  
    };  

    #endif  
    #include "stdafx.h"  
    #include "MySQLInterface.h"  


    //構造函數 初始化各個變量和數據  
    MySQLInterface::MySQLInterface():  
        errorNum(0),errorInfo("ok")  
    {  
        mysql_library_init(0,NULL,NULL);  
        mysql_init(&mysqlInstance);  
        mysql_options(&mysqlInstance,MYSQL_SET_CHARSET_NAME,"gbk");  
    }  

    MySQLInterface::~MySQLInterface()  
    {  

    }  

    //連接MySQL  
    bool MySQLInterface::connectMySQL(char* server, char* username, char* password, char* database,int port)  
    {  
        if(mysql_real_connect(&mysqlInstance,server,username,password,database,port,0,0) != NULL)  
            return true;  
        else  
            errorIntoMySQL();  
        return false;  
    }  
    //判斷數據庫是否存在,不存在則創建數據庫,并打開  
    bool MySQLInterface::createDatabase(std::string& dbname)  
    {  
        std::string queryStr = "create database if not exists ";  
        queryStr += dbname;  
        if (0 == mysql_query(&mysqlInstance,queryStr.c_str()))  
        {  
            queryStr = "use ";  
            queryStr += dbname;  
            if (0 == mysql_query(&mysqlInstance,queryStr.c_str()))  
            {  
                return true;  
            }  

        }  
        errorIntoMySQL();  
        return false;  
    }  
    //判斷數據庫中是否存在相應表,不存在則創建表  
    bool MySQLInterface::createdbTable(const std::string& query)  
    {  
        if (0 == mysql_query(&mysqlInstance,query.c_str()))  
        {  
            return true;  
        }  
        errorIntoMySQL();  
        return false;  
    }  

    //寫入數據  
    bool MySQLInterface::writeDataToDB(string queryStr)  
    {  
        if(0==mysql_query(&mysqlInstance,queryStr.c_str()))  
            return true;  
        else  
            errorIntoMySQL();  
        return false;     
    }  
    //讀取數據  
    bool MySQLInterface::getDatafromDB(string queryStr, std::vector<std::vector<std::string> >& data)  
    {  
        if(0!=mysql_query(&mysqlInstance,queryStr.c_str()))  
        {  
            errorIntoMySQL();  
            return false;  
        }  

        result=mysql_store_result(&mysqlInstance);  

        int row=mysql_num_rows(result);  
        int field=mysql_num_fields(result);  

        MYSQL_ROW line=NULL;  
        line=mysql_fetch_row(result);  

        int j=0;  
        std::string temp;  
        while(NULL!=line)  
        {     
            std::vector<std::string> linedata;  
            for(int i=0; i<field;i++)  
            {  
                if(line[i])  
                {  
                    temp = line[i];  
                    linedata.push_back(temp);  
                }  
                else  
                {  
                    temp = "";  
                    linedata.push_back(temp);  
                }  
            }  
            line=mysql_fetch_row(result);  
            data.push_back(linedata);  
        }  
        return true;  
    }  

    //錯誤信息  
    void MySQLInterface::errorIntoMySQL()  
    {  
        errorNum=mysql_errno(&mysqlInstance);  
        errorInfo=mysql_error(&mysqlInstance);  
    }  

    //斷開連接  
    void MySQLInterface::closeMySQL()  
    {  
        mysql_close(&mysqlInstance);  
    }  

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