MySQL的connector官方地址: http://dev.mysql.com/downloads/connector/
针对c++来说, 可以选择c或者c++的库.
c++的实现是参考了java的JDBC, 所以熟悉JDBC的人可以很快上手.
定义这样几个类
-
Connection
-
Driver
-
PreparedStatement
-
ResultSet
-
ResultSetMetaData
-
Statement
下载安装mysql connector c++, 启动mysql, 使用test database.
准备数据(使用官方提供的示例数据, 参考 MySQL手册 3.3.3 http://dev.mysql.com/doc/refman/5.1/zh/tutorial.html)
CREATE TABLE pet ( name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE );
导入数据(路径可以为相对路径或绝对路径)
LOAD DATA LOCAL INFILE 'pet.txt' INTO TABLE pet;
pet.txt(修改中间的间隔为 )
Fluffy Harold cat f 1993-02-04 N Claws Gwen cat m 1994-03-17 N Buffy Harold dog f 1989-05-13 N Fang Benny dog m 1990-08-27 N Bowser Diane dog m 1979-08-31 1995-07-29 Chirpy Gwen bird f 1998-09-11 N Whistler Gwen bird N 1997-12-09 N Slim Benny snake m 1996-04-29 N
示例代码
#include <iostream> #include "mysql_driver.h" #include "mysql_connection.h" #include "cppconn/driver.h" #include "cppconn/statement.h" #include "cppconn/prepared_statement.h" #include "cppconn/metadata.h" #include "cppconn/exception.h" int main() { const char* user = "root"; const char* passwd = ""; const char* host = "tcp://localhost:3306"; const char* database = "test"; try { sql::mysql::MySQL_Driver* driver = sql::mysql::get_mysql_driver_instance(); sql::Connection* conn = driver->connect(host, user, passwd); conn->setSchema(database); std::cout << "status: " << conn->isClosed() << std::endl; sql::Statement *stmt = conn->createStatement(); sql::ResultSet *res = stmt->executeQuery("select 1;"); while (res->next()) { std::cout << res->getInt(1) << std::endl; } res = stmt->executeQuery("select * from pet;"); while (res->next()) { std::cout << res->getString(1) << ","; std::cout << res->getString(2) << ","; std::cout << res->getString(3) << ","; std::cout << res->getInt(4) << ","; std::cout << res->getString(5) << ","; std::cout << res->getString(6) << std::endl; } delete res; delete stmt; delete conn; } catch (sql::SQLException& e) { std::cout << "# ERR: SQLException in " << __FILE__; std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl; std::cout << "# ERR: " << e.what(); std::cout << " (MySQL error code: " << e.getErrorCode(); std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl; } return 0; }
运行结果
status: 0 1 Fluffy,Harold,cat,0,1993-02-04, Claws,Gwen,cat,0,1994-03-17, Buffy,Harold,dog,0,1989-05-13, Fang,Benny,dog,0,1990-08-27, Bowser,Diane,dog,0,1979-08-31,1995-07-29 Chirpy,Gwen,bird,0,1998-09-11, Whistler,Gwen,bird,0,1997-12-09, Slim,Benny,snake,0,1996-04-29,
参考文档:
- 官方手册: http://dev.mysql.com/doc/refman/5.6/en/connector-cpp.html
- MySQL Connector/C++文档翻译: http://www.cnblogs.com/dvwei/archive/2013/04/18/3029464.html