之前写过一个 sql 文本转换为 c++ sqlite 数据库接口的脚本
https://blog.csdn.net/qq_23880193/article/details/82720868
但是发现, 只要换一种数据库, 就需要专门为这个数据库写一个脚本, 但是明明都是一样的东西, 所以就想到把接口抽象出来, 然后只写一次脚本, 如果要更换数据库, 只需要写一下按照定义的数据库接口实现虚函数, 就可以直接使用脚本生成的接口 (我已经写了两个驱动了, 分别是 mysql 和 sqlite 的 -> 这两个驱动直接依赖的官方 api)
接口定义: https://github.com/MwlLj/cpp_component/tree/master/component/header/sql/sql.h
mysql 驱动: https://github.com/MwlLj/cpp_component/tree/master/component/src/sql/source/mysqlimp.cpp
sqlite 驱动: https://github.com/MwlLj/cpp_component/tree/master/component/src/sql/source/sqliteimp.cpp
测试源码:
https://github.com/MwlLj/cpp_component/tree/master/component/src/sql/sql_test
最重要的就是下面两句
sql::ISql *sql = new sql::CSqliteSql();
user_info::CDbHandler dbHandler("test.db", sql);
第一行: sql::CSqliteSql() 就是 我写的sqlite的驱动
第二行: 表示将 驱动注册到 接口类中 (其中 user_info::CDbHandler 就是脚本生成的接口类)
例: 添加用户
user_info::CAddUserinfoInput input;
input.setUsername("jake");
input.setUserage(30);
dbHandler.addUserinfo(input);
脚本所在位置:
https://github.com/MwlLj/sql2cpp
执行方式:
1. 下载 https://github.com/MwlLj/scriptbase , 并重命名为 base
2. 下载 https://github.com/MwlLj/sql2cpp (第 1, 2 步骤中, base 和 sql2cpp 在同一级目录)
3. 进入到 https://github.com/MwlLj/sql2cpp , 这个目录下面有一个 example
运行:
python main.py -f ./example_sql/user_info.sql -ho ./example_sql/output/include -co ./example_sql/output/source -create
说明:
-f: 后面接 *.sql 的文件路径
-ho: 指定头文件的数据目录
-co: 指定源文件的数据库目录
-create/-update: 创建/更新