7.1 先决条件和背景信息

本部分描述了在完成其余教程部分之前必须满足的先决条件,并展示了如何设置作为教程应用程序基础的框架代码。

这些教程引用了 world数据库中的表和示例数据,您可以从 MySQL 文档页面 的示例数据库部分 下载这些数据。

每个教程应用程序都使用一个由以下代码组成的框架。/* INSERT TUTORIAL CODE HERE! */这些示例在块内 的行中有所不同, try每个应用程序都用特定于应用程序的代码替换了该行。

#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
/* uncomment for applications that use vectors */
/*#include <vector>*/

#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

#define EXAMPLE_HOST "localhost"
#define EXAMPLE_USER "worlduser"
#define EXAMPLE_PASS "worldpass"
#define EXAMPLE_DB "world"

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 << "Connector/C++ tutorial framework..." << endl;
  cout << endl;

  try {

    /* INSERT TUTORIAL CODE HERE! */

  } catch (sql::SQLException &e) {
    /*
      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;
    /* what() (derived from std::runtime_error) fetches 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;
}

要将框架代码作为独立程序来试用,请使用以下过程:

  1. 将框架代码复制并粘贴到一个文件中,例如 framework.cpp. 编辑 #define语句以反映您的连接参数(服务器、用户、密码、数据库)。此外,因为该文件包含这些参数,请将其访问模式设置为只对您自己可读。

  2. 编译框架。例如,在 macOS 上,命令可能如下所示(在一行中输入命令):

    $> g++ -o framework
      -I/usr/local/include -I/usr/local/include/cppconn
      framework.cpp -lmysqlcppconn

    根据您的系统的需要调整命令。后面的教程应用程序需要类似的命令。

  3. 要运行该框架,请输入以下内容:

    $> ./framework

    您将看到一条简单的消息:

    Connector/C++ tutorial framework...
    
    Done.

您现在可以继续学习教程了。