原文地址: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; }