天天看點

vc++與MySQL資料庫的連接配接(windows)

vc++與MySQL資料庫的連接配接

1.MySQL資料庫的安裝

 你可以從MySQL的官網上或者從如下位址下載下傳MySQL的資料庫安裝包。本文以mysql-5.0.27-win32為例。下載下傳完之後解壓安裝。注意:在安裝的過程中,選擇安裝“完全版”(complete),不要選擇預設的“典型”。否者,沒有c++相關的連接配接庫。然後一直點next即可。安裝過程中讓你注冊,你就按部就班的做就行了。安裝完之後的檔案目錄如下:

 [Image]

vc++與MySQL資料庫的連接配接(windows)

2.資料庫的建立

 你可以直接用MySQL的指令行視窗去建立一個資料庫和一個表。但是,我強烈推薦你用可視化的工具(你可以去搜一下)。在這裡,我之前安裝過wamp5就直接用網頁版的phpmyadmin工具。如果你安裝過wamp5,直接在浏覽器中輸入:http://localhost/phpmyadmin/即可。然後我們建立一個名為testdb的資料庫再在其中建立一個表:name_table.然後新增資料:zhb 22studentsnjupt

 [Image][Image]

vc++與MySQL資料庫的連接配接(windows)
vc++與MySQL資料庫的連接配接(windows)

3.VC++6.0的配置

本文以經典的vc++6.0為例。(當然,VS2005 2008 2010等,也是這樣配置)。打開vc++6.0,工具->選項->目錄(頁籤),在其Include files添加MySQL的include路徑。如我的MySQL的include檔案夾的路徑為:C:\Program Files\MySQL\MySQL Server 5.0\include。切換下拉框,選擇Library files,添加MySQL的lib路徑。如我的為:C:\Program Files\MySQL\MySQL Server 5.0\lib\opt

4.程式設計連接配接資料庫并查詢

[c++ codes]

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h> 
#include <iostream>
#pragma comment(lib,"libmysql.lib")//連接配接MysQL需要的庫
using namespace std;
int main()
{
    const char user[] = "root";         //username
    const char pswd[] = "*********";    //password
    const char host[] = "localhost";    //or"127.0.0.1"
    const char table[] ="testdb";       //database
    unsigned int port = 3306;           //server port        
    MYSQL myCont;
    MYSQL_RES *result;
    MYSQL_ROW sql_row;
    MYSQL_FIELD *fd;
    char column[32][32];
    int res;
    mysql_init(&myCont);
    if(mysql_real_connect(&myCont,host,user,pswd,table,port,NULL,0))
    {
        cout<<"connect succeed!"<<endl;
        mysql_query(&myCont, "SET NAMES GBK"); //設定編碼格式,否則在cmd下無法顯示中文
        res=mysql_query(&myCont,"select * from name_table");//查詢
        if(!res)
        {
            result=mysql_store_result(&myCont);//儲存查詢到的資料到result
            if(result)
            {
                int i,j;
                cout<<"number of result: "<<(unsigned long)mysql_num_rows(result)<<endl;
                for(i=0;fd=mysql_fetch_field(result);i++)//擷取列名
                {
                    strcpy(column[i],fd->name);
                }
                j=mysql_num_fields(result);
                for(i=0;i<j;i++)
                {
                    printf("%s\t",column[i]);
                }
                printf("\n");
                while(sql_row=mysql_fetch_row(result))//擷取具體的資料
                {
                    for(i=0;i<j;i++)
                    {
                        printf("%s\n",sql_row[i]);
                    }
                    printf("\n");
                }
            }
        }
        else
        {
            cout<<"query sql failed!"<<endl;
        }
    }
    else
    {
        cout<<"connect failed!"<<endl;
    }
    if(result!=NULL) mysql_free_result(result);//釋放結果資源
    mysql_close(&myCont);//斷開連接配接
    return 0;
}      

實驗結果

[Image]