newobj跨平台开发框架:https://github.com/Liuccysdgg/newobj
上一章已经搭建起运行环境并映射了回调函数,本文目的是搭建个人博客网站,必然少不了数据交互,所以第二章接入MYSQL数据库。
知识要点:MYSQL数据库连接、查询
一、环境安装
1、安装宝塔面板或phpstudy可快速安装mysql,mysql推荐8.0及以上版本。此处不再赘述
2、mysql建立数据库 blog 执行以下语句。
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`sex` bit(1) NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, 'newobj', '123456', b'1', 25);
SET FOREIGN_KEY_CHECKS = 1;
二、配置修改
数据库环境已经安装完成吗,接下来就可以开始程序的配置了.
1、打开 res\config.json
2、增加 mysql JSON对象。根据MYSQL安装情况修改
config.json
{
"website":[
{
"host":[
{
"host":"0.0.0.0:6699",
"ssl":false
}
],
"router":{
"threadpool":{
"queuemax":10000,
"size":5
}
}
}
],
"mysql":{
"ipaddress":"127.0.0.1",
"password":"xeMjCwGLKsdwT6A7",
"port":3306,
"username":"blog",
"database":"blog"
}
三、MYSQL示例
增加一个测试函数,读取配置文件并连接数据库,如有异常使用 std::exception 捕获。
#include <iostream>
#include "util/json.h"
#include "mysql/mysql_plus.h"
void test()
{
try
{
mysql_plus::mysql_conn_info info;
// 读配置文件
newobj::json config;
config.parse_file("./res/config.json");
// JSON配置写入结构体
info.charset = "utf8mb4";
info.database = config["mysql"]["database"].to<nstring>();
info.ipaddress = config["mysql"]["ipaddress"].to<nstring>();
info.password = config["mysql"]["password"].to<nstring>();
info.username = config["mysql"]["username"].to<nstring>();
info.port = config["mysql"]["port"].to<uint32>();
// 创建连接
mysql_plus::conn conn;
conn.start(info);
// 执行插入语句;活得SQL处理类,指针无需释放。
mysql_plus::prepare_statement *ppst = conn.setsql("INSERT INTO users(username,password,sex,age)VALUES(?,?,?,?)");
// 填充SQL中问号内容,从1开始
ppst->set_string(1,"newobj");
ppst->set_string(2,"123456");
// TRUE=男 FALSE=女
ppst->set_boolean(3,true);
ppst->set_int32(4,25);
std::cout<<"Row:"<<ppst->update()<<std::endl;
}
catch(cont std::exception&e)
{
std::cout<<e.what()<<std::endl;
}
}