如何在C++中使用SQL统计每月借阅报表(Unix时间戳存储)
统计每月借阅记录的SQL及C++调用实现
一、SQL查询语句
不同数据库对Unix时间戳的处理函数存在差异,以下是主流数据库的适配实现:
MySQL/MariaDB
SELECT DATE_FORMAT(FROM_UNIXTIME(dateOfBorrow), '%b') AS Month, COUNT(borrowingID) AS Total FROM borrow GROUP BY MONTH(dateOfBorrow), DATE_FORMAT(FROM_UNIXTIME(dateOfBorrow), '%b') ORDER BY MONTH(dateOfBorrow);
FROM_UNIXTIME(dateOfBorrow)将Unix时间戳转换为数据库日期格式DATE_FORMAT(..., '%b')生成缩写月份名(Jan、Feb等)- 按月份数字和月份名称分组,避免不同年份的同月份数据被合并;若需按年+月统计,可在GROUP BY和SELECT中添加年份字段
PostgreSQL
SELECT TO_CHAR(TO_TIMESTAMP(dateOfBorrow), 'Mon') AS Month, COUNT(borrowingID) AS Total FROM borrow GROUP BY EXTRACT(MONTH FROM TO_TIMESTAMP(dateOfBorrow)), TO_CHAR(TO_TIMESTAMP(dateOfBorrow), 'Mon') ORDER BY EXTRACT(MONTH FROM TO_TIMESTAMP(dateOfBorrow));
TO_TIMESTAMP(dateOfBorrow)将Unix时间戳转为时间类型TO_CHAR(..., 'Mon')生成缩写月份名
SQLite
SELECT strftime('%b', dateOfBorrow, 'unixepoch') AS Month, COUNT(borrowingID) AS Total FROM borrow GROUP BY strftime('%m', dateOfBorrow, 'unixepoch'), strftime('%b', dateOfBorrow, 'unixepoch') ORDER BY strftime('%m', dateOfBorrow, 'unixepoch');
strftime('%b', dateOfBorrow, 'unixepoch')直接从Unix时间戳提取缩写月份名
二、C调用示例(MySQL Connector/C)
以下代码通过MySQL官方Connector执行SQL查询,并将结果封装为结构体返回:
#include <mysqlx/xdevapi.h> #include <iostream> #include <vector> #include <string> using namespace mysqlx; using namespace std; // 存储统计结果的结构体 struct MonthlyBorrowStats { string month; int total; }; // 获取每月借阅统计数据 vector<MonthlyBorrowStats> fetchMonthlyBorrowStats(const string& host, int port, const string& user, const string& pass, const string& db) { vector<MonthlyBorrowStats> stats; try { // 建立数据库连接 Session session(host, port, user, pass); session.sql("USE " + db).execute(); // 执行SQL查询 Result result = session.sql(R"( SELECT DATE_FORMAT(FROM_UNIXTIME(dateOfBorrow), '%b') AS Month, COUNT(borrowingID) AS Total FROM borrow GROUP BY MONTH(dateOfBorrow), DATE_FORMAT(FROM_UNIXTIME(dateOfBorrow), '%b') ORDER BY MONTH(dateOfBorrow) )").execute(); // 解析查询结果 for (Row row : result) { MonthlyBorrowStats stat; stat.month = row[0].get<string>(); stat.total = row[1].get<int>(); stats.push_back(stat); } session.close(); } catch (const mysqlx::Error& err) { cerr << "数据库操作错误: " << err.what() << endl; } return stats; } int main() { // 替换为你的数据库连接信息 auto stats = fetchMonthlyBorrowStats("localhost", 3306, "root", "your_password", "library_db"); // 打印结果 cout << "月份\t借阅总数\n"; for (const auto& stat : stats) { cout << stat.month << "\t" << stat.total << "\n"; } return 0; }
编译运行
确保已安装MySQL Connector/C++,使用以下命令编译:
g++ -o borrow_stats borrow_stats.cpp -lmysqlcppconn8
运行生成的可执行文件即可查看统计结果。
内容的提问来源于stack exchange,提问作者Hafiz Suhaizal
相关产品推荐
相关产品推荐

