1 Star 0 Fork 0

蝎子莱莱xo/cpp_projects

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
oj_model_mysql.hpp 3.79 KB
一键复制 编辑 原始数据 按行查看 历史
lmx-xo 提交于 2024-04-13 19:30 +08:00 . 顶层makefile
#pragma once
#include "../comm/log.hpp"
#include "../comm/util.hpp"
// #include "include/mysql/jdbc.h"
#include <mysql/mysql.h>
// MySQL版题库
namespace ns_model_mysql
{
using namespace ns_log;
using namespace ns_util;
// using namespace sql;
// 题目信息的结构体
struct Question
{
string number; // 题目编号,唯一
string title; // 题目标题
string star; // 题目难度
string desc; // 题目的描述
string header; // 题目预设给用户的在线编辑器的代码
string tail; // 题目的测试用例,需要和header拼接,形成完整代码
int cpu_limit; // 题目的时间要求(s)
int mem_limit; // 题目的空间要求(KB)
};
// 表名
const string table_name = "oj_questions";
// MySQL链接函数的参数
const string host = "127.0.0.1";
const string user = "oj_client";
const string password = "wtf972312035lmx";
const string database = "oj";
const int port = 3306;
class Model
{
public:
Model()
{
}
bool QueryMySQL(const string &sql, vector<Question> *out)
{
// 创建MySQL句柄
MYSQL *my = mysql_init(nullptr);
// 链接数据库
if (nullptr == mysql_real_connect(my, host.c_str(), user.c_str(),
password.c_str(), database.c_str(), port, nullptr, 0))
{
LOG(FATAL) << " 数据库链接失败"
<< "\n";
return false;
}
// 设置默认编码格式
mysql_set_character_set(my, "utf8");
LOG(INFO) << " 数据库链接成功"
<< "\n";
// 执行sql语句
if (0 != mysql_query(my, sql.c_str()))
{
LOG(WARNING) << " 数据库查询语句执行失败"
<< "\n";
return false;
}
// 提取并分析结果
MYSQL_RES *res = mysql_store_result(my);
int rows = mysql_num_rows(res); // 获得行数量
int cols = mysql_num_fields(res); // 获得列数量
// 拿到结果:获取一行数据,MYSQL_ROW其实就是char **,相当于一个char* 的数组,数组元素是每一列的内容
Question q;
for (int i = 0; i < rows; i++)
{
MYSQL_ROW row = mysql_fetch_row(res);
q.number = row[0];
q.title = row[1];
q.star = row[2];
q.desc = row[3];
q.header = row[4];
q.tail = row[5];
q.cpu_limit = atoi(row[6]);
q.mem_limit = atoi(row[7]);
out->push_back(q);
}
//释放结果空间
mysql_free_result(res);
//关闭连接
mysql_close(my);
return true;
}
// 获取所有题目
bool GetAllQuestions(std::vector<Question> *out)
{
string sql = "select * from ";
sql += table_name;
return QueryMySQL(sql, out);
}
// 获取指定题目
bool GetOneQuestion(const string &number, Question *q)
{
bool flag = false;
string sql = "select * from ";
sql += table_name;
sql += " where number=";
sql += number;
vector<Question> result;
if (QueryMySQL(sql, &result))
{
if (result.size() == 1)
{
*q = result[0];
flag = true;
}
}
return flag;
}
~Model()
{
}
};
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/lmx-xo/cpp_projects.git
git@gitee.com:lmx-xo/cpp_projects.git
lmx-xo
cpp_projects
cpp_projects
master

搜索帮助