標籤:style blog http io ar color os sp for
原文地址:http://blog.csdn.net/nupt123456789/article/details/8043091
1.MySQL資料庫的安裝
你可以從MySQL的官網上或者從如下地址下載MySQL的資料庫安裝包(http://download.csdn.net/detail/nuptboyzhb/4619847)。本文以mysql-5.0.27-win32為例。下載完之後解壓安裝。注意:在安裝的過程中,選擇安裝“完全版”(complete),不要選擇預設的“典型”。否者,沒有c++相關的串連庫。然後一直點next即可。安裝過程中讓你註冊,你就按部就班的做就行了。
2.資料庫的建立
你可以直接用MySQL的命令列視窗去建立一個資料庫和一個表。但是,我強烈推薦你用可視化的工具(你可以去搜一下)。在這裡,我之前安裝過wamp5就直接用網頁版的phpmyadmin工具。如果你安裝過wamp5,直接在瀏覽器中輸入:http://localhost/phpmyadmin/即可。然後我們建立一個名為testdb的資料庫再在其中建立一個表:name_table.然後新增資料:zhb 22studentsnjupt
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.編程串連資料庫並查詢
#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;}
【轉】VC++與MySQL資料庫的串連