MySQL connector/C++

来源:互联网 发布:淘宝聊天工具下载 编辑:程序博客网 时间:2024/05/21 07:50

首先去MySQL官网下载MySQL connector/C++

http://dev.mysql.com/downloads/connector/cpp/

根据自己系统平台下载相应的版本。文件夹名字太长,将“mysql-connector-c++-noinstall-1.0.5-win32”改为“mysql”。

下面要配置vs2008的环境。

1. 项目属性页->C/C++->General->Additional Include Directories。将mysql\include目录添加进去。

2. 项目属性页->Linker->General->Additional Library Directories。将mysql\lib与$MySQL\bin目录添加进去。

3. 项目属性页->Linker->Input->Additional Dependencies。添加这两项mysqlcppconn.lib,mysqlcppconn-static.lib(mysql\lib目录下的两个.lib文件)

4. 将mysql\lib下的mysqlcppconn.dll文件与$MySQL\bin\libmySQL.dll复制到windows\system32文件夹下。

环境配置完毕。

在连接数据库之前,先建立一张表。 (其实这些可以在代码中完成,我这样是为了让测试代码尽可能简练易查错)

打开控制台,输入mysql -u root -p,输入密码。

查看当前已有的数据库。(SQL语句末尾加上';'表示立即执行当前语句。)
mysql> show databases;

创建数据库
mysql> create database test;

使用数据库(这句不能加分号)
mysql> use test

查看已有的表
mysql> show tables;

创建表
mysql> create table testuser ( id INT, name CHAR(20));

插入数据
mysql> insert into testuser(id, name) values(1001, 'google');
mysql> insert into testuser(id, name) values(1002, 'kingsoft');
mysql> insert into testuser(id, name) values(1003, 'firefox');

现在在C++中查询这些数据

  1. #include "stdafx.h"  
  2. #include <mysql_connection.h>  
  3. #include <mysql_driver.h>  
  4. #include <statement.h>  
  5. using namespace sql;  
  6. using namespace std;  
  7. void RunConnectMySQL()   
  8. {  
  9.     mysql::MySQL_Driver *driver;  
  10.     Connection *con;  
  11.     Statement *state;  
  12.     ResultSet *result;  
  13.     // 初始化驱动  
  14.     driver = sql::mysql::get_mysql_driver_instance();  
  15.     // 建立链接  
  16.     con = driver->connect("tcp://127.0.0.1:3306""root""123");  
  17.     state = con->createStatement();  
  18.     state->execute("use test");  
  19.     // 查询  
  20.     result = state->executeQuery("select * from testuser where id < 1002");  
  21.     // 输出查询  
  22.     while(result->next())  
  23.     {  
  24.         int id = result->getInt("ID");  
  25.         string name = result->getString("name");  
  26.         cout << id << " : " << name << endl;  
  27.     }  
  28.     delete state;  
  29.     delete con;  
  30. }  
  31. int _tmain(int argc, _TCHAR* argv[])  
  32. {  
  33.     RunConnectMySQL();  
  34.     getchar();  
  35.     return 0;  
  36. }  
原创粉丝点击