Vs2010中使用c++连接mysql数据库

艾玛,,,c#下简单多了,可是为何c++这么麻烦的,折腾了好久才弄好的….下面分享给大家我的过程.
1.在mysql官网下载connector.记住,要下载安装版的.因为免安装的没有opt目录
2.因为这个会用到动态指针,所以必须下载boost库并安装
接下来就是环境变量的配置
动态链接的debug设置和release设置是相同的,具体如下:

(1)项目属性页,“c/c++”-“常规”-“附加包含目录”添加相关头文件路径:

D:mysql_connectorboost_1_55_0

D:mysql_connectorMySQL Connector C++ 1.1.3includecppconn

D:mysql_connectorMySQL Connector C++ 1.1.3include

(2)项目属性页,“链接器”-“常规”-“附加库目录”添加库文件mysqlcppconn.lib的路径

D:mysql_connectorMySQL Connector C++ 1.1.3libopt

D:mysql_connectorMySQL Connector C++ 1.1.3lib

“链接器”-“输入”-“附加依赖项”添加库文件

mysqlcppconn.lib

mysqlcppconn-static.lib

( 3 )将目录D:mysql_connectorMySQL Connector C++ 1.1.3libopt下的文件拷贝到工程的debeg目录下。

将mysql安装目录里面的libmysql.dll也复制到工程的debeg目录下。

大功告成!接下来就是数据库和代码了,一并发给大家

数据库名为student,表名为students,

下面是创建表的代码


create table students
(
 id int(3) auto_increment not null primary key,
 name varchar(30) not null,
 address varchar(40) default '西安'
);

然后大家往表里面插入一些数据就ok了,下面是c++的代码


#include <mysql_connection.h>
#include <mysql_driver.h>
#include <statement.h>
#include <cppconn/exception.h>&nbsp;

using namespace std;
using namespace sql;

int main()
{

	mysql::MySQL_Driver *drive;
	Connection *con;
	Statement *state;
	ResultSet *result;
	drive = sql::mysql::get_mysql_driver_instance();
	try
	{
		con = drive->connect("tcp://192.168.142.129:3306", "root", "rootpassword");
		con->setSchema("student");&nbsp;&nbsp;
		con->setClientOption("characterSetResults","gbk");//设置字符格式

		state = con->createStatement();

		//	state->execute("use student");
		result = state->executeQuery("select * from students");
		while(result->next())
		{
			int id = result->getInt("id");
			string name = result->getString("name");
			string address = result->getString("address");
			cout<<"name "<<name<<" id "<<id<<" address "<<address<<endl;
		}
		delete result;
		delete state;
		delete con;
	}
	catch(sql::SQLException &ex)
	{
		cout<<"error: "<<ex.what()<<endl;
		cout<<"MySQL error code: "<<ex.getErrorCode()<<endl;
		cout<<"SQLState: "<<ex.getSQLState()<<endl;
	}

	getchar();
	return 0;
}

好了,就是这样.大家试试.

Posted from WordPress for Android

发表评论

电子邮件地址不会被公开。 必填项已用*标注