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++中查詢這些資料
- #include "stdafx.h"
- #include <mysql_connection.h>
- #include <mysql_driver.h>
- #include <statement.h>
- usingnamespace sql;
- usingnamespace std;
- void RunConnectMySQL()
- {
- mysql::MySQL_Driver *driver;
- Connection *con;
- Statement *state;
- ResultSet *result;
- // 初始化驅動
- driver = sql::mysql::get_mysql_driver_instance();
- // 建立連結
- con = driver->connect("tcp://127.0.0.1:3306", "root", "123");
- state = con->createStatement();
- state->execute("use test");
- // 查詢
- result = state->executeQuery("select * from testuser where id < 1002");
- // 輸出查詢
- while(result->next())
- {
- int id = result->getInt("ID");
- string name = result->getString("name");
- cout << id << " : " << name << endl;
- }
- delete state;
- delete con;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- RunConnectMySQL();
- getchar();
- return 0;
- }