用C++开发MYSQL应用

简单的介绍如何用Visual Studio C++开发MYSQL的应用。为新手指明开发环境的准备和资源的位置。
首先是准备工作。需要下载三个开发库:

  1. 去官方网站下载mysql-connector/c++。有多个版本,我下载的是mysql-connector-c++-noinstall-1.1.0-win32-vs2005.zip。connector-c++提供了两个lib,mysqlcppconn.lib和mysqlcppconn-static.lib,不幸的是最终运行的时候他们都需要libmysql.dll。
  2. 所以还需要下载connector/c。同样有多个版本可以选择,我下载的是mysql-connector-c-noinstall-6.0.2-win32-vs2005.zip。把两个压缩包解压到同一个地方,开发包就准备好了,但是准备工作还没有完成。
  3. 你还需要下载boost库才可以编译程序,因为新的版本的connector中使用了boost。
    然后是工程的配置, 主要是选择哪个lib。我选择使用mysqlcppconn.lib+libmysql.lib。其他的组合在visual studio 2010下都会有很多链接错误。相信所有的错误都是可以通过配置解决的,具体策略视需求而定。

最后,mysql网站提供了一些manualexample

下面是一个简单的例子:

#include "stdafx.h"

#include "mysql_connection.h"
#include "mysql_driver.h"

#define EXAMPLE_HOST "xxx"
#define EXAMPLE_USER "xxxxx"
#define EXAMPLE_PASS "xxxxxx"
#define EXAMPLE_DB "xxxxxx"

using namespace std;

int main(int argc, const char **argv)
{

string url(argc >= 2 ? argv[1] : EXAMPLE_HOST);
const string user(argc >= 3 ? argv[2] : EXAMPLE_USER);
const string pass(argc >= 4 ? argv[3] : EXAMPLE_PASS);
const string database(argc >= 5 ? argv[4] : EXAMPLE_DB);

cout < < "Connecting to MYSQL server..." << endl;
cout << endl;

try {

sql::mysql::MySQL_Driver *driver;
sql::Connection *con;

driver = sql::mysql::get_driver_instance();
con = driver->connect(EXAMPLE_HOST, EXAMPLE_USER, EXAMPLE_PASS);

cout < < "Done! Querying..." << endl;

sql::Statement *stmt;
stmt = con->createStatement();
stmt->execute("USE " EXAMPLE_DB);
//stmt->execute("DROP TABLE IF EXISTS test");
//stmt->execute("SELECT * FROM `test` LIMIT 0, 30 ");

sql::ResultSet *res;
res = stmt->executeQuery("SELECT * FROM test LIMIT 0, 30 ");

cout < < "Done! Printing..." << endl;

while (res->next()) {
//// You can use either numeric offsets...
//cout < < "id = " << res->getInt(1); // getInt(1) returns the first column
// ... or column names for accessing results.
// The latter is recommended.
cout < < "Project: " << res->getString("project") < < endl;
cout << "Deadline:" << res->getString("deadline") < < endl;
cout << "Price: " << res->getString("price") < < endl;
cout << "People: " << res->getString("people") < < endl;
}

delete res;

delete stmt;

delete con;

} catch (sql::SQLException &e) {
/*
The MySQL Connector/C++ throws three different exceptions:

- sql::MethodNotImplementedException (derived from sql::SQLException)
- sql::InvalidArgumentException (derived from sql::SQLException)
- sql::SQLException (derived from std::runtime_error)
*/
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
/* Use what() (derived from std::runtime_error) to fetch the error message */
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;

return EXIT_FAILURE;
}

cout << "Done." << endl;
return EXIT_SUCCESS;
}