1. 程式人生 > >MySQL connector/C++的用法

MySQL connector/C++的用法

原文地址:

首先去MySQL官網下載MySQL connector/C++

根據自己系統平臺下載相應的版本。資料夾名字太長,將“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. usingnamespace sql;  
  6. usingnamespace 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. }