基于websocket的多用户网页五子棋(四)
一.前期回顾
对于前面内容不太了解的,可以去看一看下面的:https://blog.csdn.net/weixin_60668256/article/details/152447607?fromshare=blogdetail&sharetype=blogdetail&sharerId=152447607&sharerefer=PC&sharesource=weixin_60668256&sharefrom=from_link
二.数据管理模块设计
1.数据库设计
这里的密码在设置之后会变成一串乱序的字符,所以要开128个varchar,而且为了设置用户名不重复,我们这里将username设置成为unique key
drop database if exists gobang;create database if not exists gobang;use gobang;create table if not exists user(id int primary key auto_increment,username varchar(32) unique key not null,password varchar(128) not null,score int,table_count int,win_count int
);
2.数据管理模块的封装与实现
代码实现:
#ifndef __M_DB_H__
#define __M_DB_H__#include <assert.h>
#include <mutex>
#include "util.hpp"class user_table{
private:MYSQL *_mysql; //mysql操作句柄std::mutex _mutex;//互斥锁保护数据库的访问操作
public:user_table(const std::string &host,const std::string& username,const std::string& password,const std::string& dbname,uint16_t port = 3306){_mysql = mysql_util::mysql_create(host,username,password,dbname,port);assert(_mysql != NULL);}~user_table(){mysql_util::mysql_destory(_mysql);_mysql = NULL;}//注册时新增用户bool insert(Json::Value &user){#define INSERT_USER "insert user values(null,'%s',SHA2('%s',256),1000,0,0);"//进行执行增加功能if(user["password"].isNull() || user["username"].isNull()){DLOG("INPUT PASSWORD OR USERNAME");return false;}char sql[4096] = {0};sprintf(sql,INSERT_USER,user["username"].asCString(),user["password"].asCString());bool ret = mysql_util::mysql_exec(_mysql,sql);if(ret == false){DLOG("insert user info failed!!\n");return false;}return true;}//登录验证,并返回详细的用户信息bool login(Json::Value &user){//以用户名和密码共同作为查询过滤的条件,查询到数据则表示用户名和密码一致,没有信息表示用户名密码错误#define LOGIN_USER "select id,score,total_count,win_count from user where username='%s' and password=SHA2(