您的位置:首页 > 编程语言 > C语言/C++

vc++与MySQL数据库的连接(C库API方法,非odbc)

2014-04-02 12:22 337 查看
1.MySQL数据库的安装

你可以从MySQL的官网上或者从如下地址下载MySQL的数据库安装包(http://download.csdn.net/detail/nuptboyzhb/4619847)。本文以mysql-5.0.27-win32为例。下载完之后解压安装。注意:在安装的过程中,选择安装“完全版”(complete),不要选择默认的“典型”。否者,没有c++相关的连接库。然后一直点next即可。安装过程中让你注册,你就按部就班的做就行了。安装完之后的文件目录如下:

[Image]



2.数据库的建立

你可以直接用MySQL的命令行窗口去建立一个数据库和一个表。但是,我强烈推荐你用可视化的工具(你可以去搜一下)。在这里,我之前安装过wamp5就直接用网页版的phpmyadmin工具。如果你安装过wamp5,直接在浏览器中输入:http://localhost/phpmyadmin/即可。然后我们新建一个名为testdb的数据库再在其中新建一个表:name_table.然后新增数据:zhb 22studentsnjupt

[Image][Image]





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]

[cpp] view
plaincopy

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: