C++ 讀寫MySQL經典

來源:互聯網
上載者:User
       看過很多C或是C++操作MySQL資料庫的文章,大部分太吃力了,甚至有一部分根本沒有很好的組織文字,初學者比較難以接受,即使是C++或是C高手也是比較難看懂。寫這篇文章的目的不是別的,就一個,告訴您用MySQL的C API直接操作MySQL資料,並做了比較高效的封裝,可以協助開發人員大幅度提高採用MySQL的C API操作MySQL資料庫的效率。直接進入主題:1、  準備工作MySQL資料庫安裝之後在/MySQL Server 5.0/lib/opt目錄下有所需要的各種檔案,我們需要的只是以下幾個:libmysql.liblibmysql.dll同時需要/MySQL Server 5.0/include目錄下的幾個檔案:mysql_version.hmy_list.hmysql_com.hmysql_time.hmysql.hmy_alloc.htypelib.h 準備Socket的基本檔案在VC的安裝目錄Microsoft Visual Studio/VC98/Lib下找到:WS2_32.LIB 把這些檔案先準備好 2、  使用VC的AppWizard建立一個Win32 Console Application,其實可以是Dialog工程或是其他類型工程,比如工程取名CMySQL3、  把剛才準備好的檔案拷貝你的工程目錄下,和普通的CPP檔案在同一個目錄即可4、  建立之後,在VC的功能表列點擊Project(項目)->Settings(設定),彈出對話方塊,選擇Link標籤進入Link設定,在Object/library modules 的框裡面加入libmysql.lib[有個空格]WS2_32.LIB5、    在工程建立添加以下兩個檔案: 第一個檔案標頭檔:VspdCTOMySQL.h/****************************MYSQL IN C*******************************//*************************2007 -03 -07 *******************************//*************************李克喜**************************************/  #include <stdio.h>#include <string>#include <afxsock.h>#include "mysql.h" using   namespace   std;class VspdCToMySQL {public:              //變數       MYSQL mysql;         /*       建構函式和稀構函數       */       VspdCToMySQL();       ~VspdCToMySQL();        /*       主要的功能:       初始化資料庫       串連資料庫       設定字元集        入口參數:       host :MYSQL伺服器IP       port:資料庫連接埠       Db:資料庫名稱       user:資料庫使用者       passwd:資料庫使用者的密碼       charset:希望使用的字元集       Msg:返回的訊息,包括錯誤訊息        出口參數:       int :0表示成功;1表示失敗       */       int ConnMySQL(char *host,char * port,char * Db,char * user,char* passwd,char * charset,char * Msg);        /*       主要的功能:       查詢資料        入口參數:       SQL:查詢的SQL語句       Cnum:查詢的列數       Msg:返回的訊息,包括錯誤訊息        出口參數:       string 準備放置返回的資料,多條記錄則用0x06隔開,多個欄位用0x05隔開       如果 返回的長度= 0,責表示舞結果       */       string SelectData(char * SQL,int Cnum ,char * Msg);              /*       主要功能:       插入資料              入口參數       SQL:查詢的SQL語句       Msg:返回的訊息,包括錯誤訊息        出口參數:       int :0表示成功;1表示失敗       */       int InsertData(char * SQL,char * Msg);        /*       主要功能:       修改資料              入口參數       SQL:查詢的SQL語句       Msg:返回的訊息,包括錯誤訊息        出口參數:       int :0表示成功;1表示失敗       */       int UpdateData(char * SQL,char * Msg);         /*       主要功能:       刪除資料              入口參數       SQL:查詢的SQL語句       Msg:返回的訊息,包括錯誤訊息        出口參數:       int :0表示成功;1表示失敗       */       int DeleteData(char * SQL,char * Msg);              /*       主要功能:       關閉資料庫連接       */       void CloseMySQLConn(); };                 第二個檔案實現檔案:VspdCTOMySQL.cpp   /****************************MYSQL IN C*******************************//*************************2007 -03 -07 *******************************//*************************李克喜**************************************/ #include "stdafx.h"#include "VspdCTOMySQL.h" VspdCToMySQL::VspdCToMySQL(){} VspdCToMySQL::~VspdCToMySQL(){} //初始化資料int VspdCToMySQL::ConnMySQL(char *host,char * port ,char * Db,char * user,char* passwd,char * charset,char * Msg){       if( mysql_init(&mysql) == NULL )        {               Msg = "inital mysql handle error";               return 1;        }             if (mysql_real_connect(&mysql,host,user,passwd,Db,0,NULL,0) == NULL)        {               Msg = "Failed to connect to database: Error";               return 1;        }             if(mysql_set_character_set(&mysql,"GBK") != 0)       {              Msg = "mysql_set_character_set Error";              return 1;       }       return 0;} //查詢資料string VspdCToMySQL::SelectData(char * SQL,int Cnum,char * Msg){       MYSQL_ROW m_row;     MYSQL_RES *m_res;     char sql[2048];     sprintf(sql,SQL);        int rnum = 0;       char rg = 0x06;//行隔開       char cg = {0x05};//欄位隔開        if(mysql_query(&mysql,sql) != 0)        {               Msg = "select ps_info Error";               return "";        }        m_res = mysql_store_result(&mysql);         if(m_res==NULL)        {               Msg = "select username Error";               return "";        }        string str("");       while(m_row = mysql_fetch_row(m_res))        {               for(int i = 0;i < Cnum;i++)              {                     str += m_row[i];                     str += rg;              }              str += rg;                            rnum++;       }         mysql_free_result(m_res);         return str;} //插入資料int VspdCToMySQL::InsertData(char * SQL,char * Msg){       char sql[2048];     sprintf(sql,SQL);        if(mysql_query(&mysql,sql) != 0)        {               Msg = "Insert Data Error";               return 1;        }        return 0;} //更新資料int VspdCToMySQL::UpdateData(char * SQL,char * Msg){       char sql[2048];     sprintf(sql,SQL);        if(mysql_query(&mysql,sql) != 0)        {               Msg = "Update Data Error";               return 1;        }        return 0;} //刪除資料int VspdCToMySQL::DeleteData(char * SQL,char * Msg){       char sql[2048];     sprintf(sql,SQL);        if(mysql_query(&mysql,sql) != 0)        {               Msg = "Delete Data error";              return 1;        }        return 0;} //關閉資料庫連接void VspdCToMySQL::CloseMySQLConn(){       mysql_close(&mysql); }  6、 在main函數,(如果是其他工程級不是main了,可能是一個按鈕裡面的代碼塊)添加      一些代碼,添加之後如下:#include "stdafx.h"#include "VspdCTOMySQL.h" int main(int argc, char* argv[]){    char* host="MYSQL伺服器IP";     char* user="root";     char* port ="3306";    char* passwd="使用者密碼";     char* dbname="資料庫名稱";     char* charset = "GBK";//支援中文    char* Msg = "";//訊息變數    //初始化    VspdCToMySQL * vspdctomysql = new VspdCToMySQL;    if(vspdctomysql->ConnMySQL(host,port,dbname,user,passwd,charset,Msg) == 0)           printf("串連成功/r/n");    else           printf(Msg);        //查詢    char * SQL = "SELECT ids,username,passwd,address FROM vcaccesstest";    string str = vspdctomysql->SelectData(SQL,4,Msg);    if( str.length() > 0 )    {           printf("查詢成功/r/n");           printf(str.data());           printf("/r/n");    }    else    {           printf(Msg);    }    //插入    SQL = "insert into vcaccesstest(ids,username,passwd,address) values(4,'我的','123210','測試地址')";    if(vspdctomysql->InsertData(SQL,Msg) == 0)           printf("插入成功/r/n");    //更新    SQL = "update vcaccesstest set username = '修改了',passwd='2345' where ids = 3 ";    if(vspdctomysql->UpdateData(SQL,Msg) == 0)           printf("更新成功/r/n");    //刪除    SQL = "delete from vcaccesstest where ids = 3 ";    if(vspdctomysql->DeleteData(SQL,Msg) == 0)           printf("刪除成功/r/n");     vspdctomysql->CloseMySQLConn();     return 0;}  7、 資料庫表確認表存在,(程式中的表和欄位是我的資料庫裡面的內容,你要自己搞定你的SQL語句了,你可以看main函數裡面的SQL變數的內容。8、 編譯,運行,一切ok。9、 總結,你要做的事情很少了,兩個主要的檔案寫好了,你看例子調用即可,其他MySQL的庫檔案和附加檔案別人也為您準備好了,移植到其他系統也是很簡單的,比如移植到Linux和Unix下也是很簡單的,VspdCTOMySQL.h和VspdCTOMySQL.cpp基本上是採用標準的C++編寫的,在別的系統可能需要做少量修改即可。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.