侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

介绍一个针对C++程序的MySQL访问库soci

数据库  /  管理员 发布于 6年前   292

一直以来,笔者都在不停寻找一种更人性化的数据库访问方式(并不是说默认的方式不好,而是有时候的确在模块化设计中不太方便)。
后来有幸在php中找到codeigniter的ActiveReord,详细参考这篇文章: 抽离CodeIgniter的数据库访问类!
然而c++却始终用着最原始的方式,昨天趁着项目要用的机会,在网上搜索了好久,总算让我找到两套c++的数据库访问框架:

   soci
   litesql

两套代码我都拿下来看了一下,litesql实现了一套完整的代码自动生成,功能强大,但是也很重;soci相对要轻量,但是同样也实现了数据结构到数据库表的映射。本人还是比较喜欢轻量的东西,所以最终选择了soci。经过这两天的试用,感觉非常不错。

官方的文档也很详细,所以这里就用我写的单元测试代码来做一下简单的讲解:
首先创建库表:

create database soci;CREATE TABLE `tb_test` ( `id` int(11) NOT NULL auto_increment, `name` varchar(32) default "", `sex` int(11) default 0, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`)); create database soci;CREATE TABLE `tb_test` ( `id` int(11) NOT NULL auto_increment, `name` varchar(32) default "", `sex` int(11) default 0, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`));

1.简单的select单条记录

TEST(soci,select_one){  try  {    session sql(mysql, "host=localhost db=soci user=dantezhu");    indicator ind;    string name = "dandan";    int sex;    sql << "select sex from tb_test where name = :name",      into(sex, ind), use(name);    ASSERT_EQ(ind, i_ok) << name;  }  catch (exception const &e)  {    FAIL()<<e.what();  }} TEST(soci,select_one){  try  {    session sql(mysql, "host=localhost db=soci user=dantezhu");    indicator ind;     string name = "dandan";    int sex;    sql << "select sex from tb_test where name = :name",      into(sex, ind), use(name);     ASSERT_EQ(ind, i_ok) << name;  }  catch (exception const &e)  {    FAIL()<<e.what();  }}

select的结果,如果成功则ind会为i_ok,同值sex被赋值;如果失败则反之

2.简单的select多条记录

TEST(soci,select_multi2){  try  {    session sql(mysql, "db=soci user=dantezhu");    indicator ind;    int count;    sql << "select count(*) from tb_test", into(count, ind);    ASSERT_EQ(ind, i_ok) << count;    if (count == 0)    {      SUCCEED();      return;    }    int sex = 1;    vector<string> vec_name(count);    vector<int> vec_sex(count);    sql << "select name,sex from tb_test where sex = :sex",      into(vec_name), into(vec_sex), use(sex);  }  catch (exception const &e)  {    FAIL()<<e.what();  }} TEST(soci,select_multi2){  try  {    session sql(mysql, "db=soci user=dantezhu");    indicator ind;     int count;    sql << "select count(*) from tb_test", into(count, ind);    ASSERT_EQ(ind, i_ok) << count;     if (count == 0)    {      SUCCEED();      return;    }     int sex = 1;    vector<string> vec_name(count);    vector<int> vec_sex(count);    sql << "select name,sex from tb_test where sex = :sex",      into(vec_name), into(vec_sex), use(sex);  }  catch (exception const &e)  {    FAIL()<<e.what();  }}

与select单条记录唯一的区别即,into()的参数是一个vector。其实用多个vector这种方式并不是一个很好的选择,后面会介绍基于数据结构的方式。

3.简单的insert

TEST(soci,insert_exist){  try  {    session sql(mysql, "db=soci user=dantezhu");    string name = "dandan";    int sex = 1;    sql << "insert into tb_test(name, sex) values(:name, :sex)",      use(name), use(sex);  }  catch (exception const &e)  {    SUCCEED()<<e.what();  }} TEST(soci,insert_exist){  try  {    session sql(mysql, "db=soci user=dantezhu");     string name = "dandan";    int sex = 1;     sql << "insert into tb_test(name, sex) values(:name, :sex)",      use(name), use(sex);  }  catch (exception const &e)  {    SUCCEED()<<e.what();  }}

insert,update,delete都有两个同样的问题:
a)affect_rows(操作的行数)没有办法返回
b)操作的id无法知道,尤其对于insert的主键是自增的情况下,无法知道插入的主键的值是多少。

update和delete都与insert相似,这里就不再多说。

接下来是这个框架的很重要的一个特性,即数据库表与数据结构绑定:

首先我们需要定义一个结构体,并告知soci怎么让列名和数据结构的字段对应起来:

struct Person{  int id;  std::string name;  int sex;};namespace soci{  template<> struct type_conversion<Person>  {    typedef values base_type;    static void from_base(values const & v, indicator /* ind */, Person & p)    {      p.id = v.get<int>("id");      p.name = v.get<std::string>("name");      p.sex = v.get<int>("sex");    }    static void to_base(const Person & p, values & v, indicator & ind)    {      v.set("id", p.id);      v.set("name", p.name);      v.set("sex", p.sex);      ind = i_ok;    }  };} struct Person{  int id;  std::string name;  int sex;}; namespace soci{  template<> struct type_conversion<Person>  {    typedef values base_type;    static void from_base(values const & v, indicator /* ind */, Person & p)    {      p.id = v.get<int>("id");      p.name = v.get<std::string>("name");      p.sex = v.get<int>("sex");    }    static void to_base(const Person & p, values & v, indicator & ind)    {      v.set("id", p.id);      v.set("name", p.name);      v.set("sex", p.sex);      ind = i_ok;    }  };}

关于

template<> struct type_conversion<Person> template<> struct type_conversion<Person>

这里,官方的文档是是有误的,我查了好长时间,按照上面的写法来写即可。

1.用数据结构来select

TEST(soci,select_obj_one){  try  {    session sql(mysql, "db=soci user=dantezhu");    indicator ind;    int count;    sql << "select count(*) from tb_test", into(count, ind);    ASSERT_EQ(ind, i_ok) << count;    string name = "dandan";    Person p;    sql << "select id,name,sex from tb_test where name = :name",      into(p, ind), use(name);    ASSERT_EQ(ind, i_ok) << name;    if (sql.got_data())    {      cout<< p.id         << ","         << p.name         << ","         << p.sex         << endl;    }  }  catch (exception const &e)  {    FAIL()<<e.what();  }} TEST(soci,select_obj_one){  try  {    session sql(mysql, "db=soci user=dantezhu");    indicator ind;     int count;    sql << "select count(*) from tb_test", into(count, ind);    ASSERT_EQ(ind, i_ok) << count;     string name = "dandan";    Person p;    sql << "select id,name,sex from tb_test where name = :name",      into(p, ind), use(name);     ASSERT_EQ(ind, i_ok) << name;     if (sql.got_data())    {      cout<< p.id         << ","         << p.name         << ","         << p.sex         << endl;    }   }  catch (exception const &e)  {    FAIL()<<e.what();  }}

2.用数据结构来进行insert

TEST(soci,insert_obj_noexist){  try  {    session sql(mysql, "db=soci user=dantezhu");    Person p = {      0,      "niuniu",      2    };    sql << "insert into tb_test(name, sex) values(:name, :sex)",      use(p);  }  catch (exception const &e)  {    FAIL()<<e.what();  }} TEST(soci,insert_obj_noexist){  try  {    session sql(mysql, "db=soci user=dantezhu");     Person p = {      0,      "niuniu",      2    };     sql << "insert into tb_test(name, sex) values(:name, :sex)",      use(p);  }  catch (exception const &e)  {    FAIL()<<e.what();  }}

整个就是这样~~下面是文中代码文件的下载路径:
http://code.google.com/p/vimercode/source/browse/#svn%2Ftrunk%2Fsoci_test

另外,虽然python下的mysql访问也算比较简单,但还是想知道是否有更Pythonic的库或接口,如果有朋友知道,欢迎不吝告知。


  • 上一条:
    在C#和MySQL中存取中文字符时避免乱码的方法
    下一条:
    MySQL的增删查改语句用法示例总结
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客