Programming Multiplayer Game - 使用Mysql++操作MySQL数据库

cover 本文简要介绍了怎么样使用Mysql++库来操作MySQL数据库。
Mysql++是官方发布的、一个为MySQL设计的C++语言的API,这个API的作用是使工作更加简单且容易。你可以从这里了解以及下载到Mysql++库的详情。在使用mysql++库之前,请确保MySQL数据库服务器已经安装成功。因为编译mysql++的过程需要MySQL数据库的include目录和lib目录。

本文使用的Mysql++的版本为: mysql++-3.1.0.tar.gz

编译Mysql++

下载到mysql++库压缩包之后,解压到本地目录。用vs2008打开解压目录下vc2008\mysql++.sln文件。配置项目mysql,使其include本地MySQL安装目录下的include目录; 其库目录包含本地MySQL安装目录下的lib目录,如下所示:
include
lib 

 

使用mysql++

在应用程序中使用mysql++库时,需要正确配置项目的include和lib包含路径。运行程序之前,要确保数据库服务器已经成功启动。

与数据库建立连接

连接的数据库名为gamedata, 位于本机,用户名为root,密码为空

    // -> Create a connection to the database
    Connection con("gamedata","127.0.0.1", "root", "");

 

显示表中的内容

数据库操作的执行都是调用Query对象。如果当前的Query对象的操作有返回结果,则应该获取返回结果;否则直接执行SQL语句即可。

void DisplayTable(Connection& con)
{
    // -> Create a query object that is bound to our connection
    Query query = con.query();

    // -> Assign the query to that object
    query << "SELECT * FROM playerdata";

    // -> Store the results from the query
    StoreQueryResult res = query.store();

    // -> Display the results to the console
    // -> Show the field headings
    cout.setf(ios::left);
    cout << setw(10) << "username"
        << setw(10) << "password"
        << setw(10) << "age" << endl;

    StoreQueryResult::iterator _it = res.begin();

    // The Result class has a read-only random access iterator
    for (; _it != res.end(); _it++)
    {
        Row& row = *_it;
        cout << setw(10) << row["username"]
        << setw(10) << row["password"]
        << setw(10) << row["age"] << endl;
    }
}

修改表中的某行

void UpdateRowByUserName(Connection& con, const char* username)
{
    Query query = con.query();

    query << "UPDATE playerdata SET password='111111' WHERE username='" << username << "';";

    query.execute();
}

向表中插入一行

void InsertRow(Connection& con, const char* username, const char* password, int age)
{
    Query query = con.query();

    query << "INSERT INTO playerdata VALUES(0, '" << username << "', '"
            << password << "', " << age << ");";

    query.execute();
}

本文源码可以从这里下载。

posted @ 2013-03-01 23:11  opencoder  阅读(350)  评论(0编辑  收藏  举报