C++连接mysql数据库

环境win32、mingw、codelite
1、下载mysql Microsoft Windows 32. (ZIP format)
http://downloads.mysql.com/archives.php
获得mysql-noinstall-5.1.45-win32.zip,解压缩。
2、用 reimp.exe将libmysql.lib转换为libmysql.a
获取reimp.exe 从http://www.qtcn.org/download/mingw-utils-0.3.tar.gz解压缩
拷贝D:mysql-5.1.45-win32liboptlibmysql.lib到 reimp目录下。在cmd进入目录并执行
reimp libmysql.lib
执行完后产生liblibmysql.a和LIBMYSQL.def
将liblibmysql.a改名为libmysql.a,并拷贝回D:mysql-5.1.45-win32libopt目录下
3、Complier–>Additional Search Path设置为

.;D:/mysql-5.1.45-win32/include;D:/MinGW/include/c++/3.4.5;D:/MinGW/include/c++/3.4.5/mingw32;D:/MinGW/include/c++3.4.5/backward;D:/MinGW/include;

4、Linker–>Libray Path设置为
D:MinGWlib;D:mysql-5.1.45-win32libopt
Linker–>Libraries设置为
libmysql;libwsock32;
5、编写程序
将D:mysql-5.1.45-win32liboptlibmysql.dll拷贝到C:WINDOWSsystem32目录下
main.cpp

#include "MySqlTestClass.h"
int main(int argc, char* argv[]){
MySqlTestClass* myClass = new MySqlTestClass("127.0.0.1","3306","root","root","test1");
myClass->testMysql();
return 0;
}

MySqlTestClass.h

class MySqlTestClass
{
protected:
char* dbAddress;
char* dbPort;
char* dbUser;
char* dbPassword;
char* dbName;

public:
MySqlTestClass();
MySqlTestClass(char* dbAddress,char* dbPort,char* dbUser,char* dbPassword,char* dbName);
void testMysql();
};

MySqlTestClass.cpp

#include <MySqlTestClass.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <winsock.h>
#include <mysql.h>


MySqlTestClass::MySqlTestClass()
{

}

MySqlTestClass::MySqlTestClass(char* dbAddress,char* dbPort,char* dbUser,char* dbPassword,char* dbName)
{
this->dbAddress=dbAddress;
this->dbPassword=dbPort;
this->dbUser=dbUser;
this->dbPassword=dbPassword;
this->dbName=dbName;
}


void MySqlTestClass::testMysql(){



MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char *query;
int t,r;
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,this->dbAddress,this->dbUser, this->dbPassword, this->dbName,0,NULL,CLIENT_MULTI_STATEMENTS))
{
printf( "Error connecting to database: %sn",mysql_error(&mysql));
}
else printf("Connected...n");
query = "select * from user";


t = mysql_real_query(&mysql,query,(unsigned int) strlen(query));
if (t)
{
printf("Error making query: %sn",
mysql_error(&mysql));
}else {
printf("[%s] made...n", query);
}
res = mysql_store_result(&mysql);
while(row = mysql_fetch_row(res))
{
for(t=0;t<mysql_num_fields(res);t++)
{
printf("%s ",row[t]);
}
printf("n");
}

printf("mysql_free_result...n");
mysql_free_result(res);



}

原创文章,转载请注明: 转载自海波无痕

本文链接地址: C++连接mysql数据库

文章的脚注信息由WordPress的wp-posturl插件自动生成

此条目发表在javaee分类目录,贴了, , , 标签。将固定链接加入收藏夹。