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 @   opencoder  阅读(354)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示