第三章 C++ SDK
3.1 环境准备
C++ SDK采用头文件形式分发,无需安装任何第三方库。只需将 sxdb_protocol.h 复制到项目include目录即可。
编译命令
Windows (MSVC)
cl /std:c++17 /I include main.cpp
Windows (MinGW)
g++ -std=c++17 -o client main.cpp -lws2_32
Linux / macOS
g++ -std=c++17 -o client main.cpp -lpthread
3.2 客户端核心类
SxdbClient是C++ SDK的核心类,封装了TCP连接、认证、SQL执行等全部功能。支持RAII资源管理,析构时自动断开连接。
方法
说明
返回值
connect(host, port)
连接服务器
bool
login(user, pass)
认证登录,获取token
bool
open_db(db)
打开指定数据库
bool
execute(db, sql)
执行DDL/DML语句
JVal
query(db, sql)
执行查询语句
JVal
close_db(db)
关闭数据库
bool
disconnect()
断开服务器连接
void
3.3 完整示例
示例:连接、建表、插入、查询
include "sxdb_protocol.h"
include
// 使用 SxdbClient 类 (定义在 protocol.h 中)
// 也可直接使用 sxdb::Protocol 类自行封装
int main() {
SxdbClient client;
// 1. 连接服务器
if (!client.connect("127.0.0.1", 31111)) {
std::cerr << "Failed to connect" << std::endl;
return 1;
}
// 2. 登录认证
if (!client.login("admin", "admin123")) {
return 1;
}
// 3. 打开数据库
client.open_db("myapp");
// 4. 创建表
client.execute("myapp",
"CREATE TABLE IF NOT EXISTS users("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name TEXT NOT NULL, age INTEGER)");
// 5. 插入数据
client.execute("myapp",
"INSERT INTO users(name,age) VALUES('\xe5\xbc\xa0\xe4\xb8\x89',25)");
// 6. 查询数据
auto result = client.query("myapp", "SELECT * FROM users");
auto& cols = result["data"]["columns"];
auto& rows = result["data"]["rows"];
for (size_t i = 0; i < rows.av.size(); i++) {
std::cout << rows[i][0].gi() << " "
<< rows[i][1].gs() << " "
<< rows[i][2].gi() << std::endl;
}
// 7. 清理
client.close_db("myapp");
client.disconnect();
return 0;
}
代码3-1 C++ 完整示例程序
运行输出
=== SXDB C++ Client Example ===
[1] Connecting to SXDB server (localhost:31111)...
Connected!
[2] Authenticating (admin/admin123)...
Authenticated!
[3] Opening database 'test'...
Database opened!
[4] Creating table 'users'...
Table created! code=0
[5] Inserting data...
Inserted 3 rows!
[6] Querying data...
id name age email
1 张三 25 zhangsan@example.com
2 李四 30 lisi@example.com
3 王五 28 wangwu@example.com
[7] Updating data...
Updated! affected=1
[8] Deleting data...
Deleted! affected=1
[Done] Disconnected from server.
图3-2 C++客户端运行结果