user表设计
字段名称 | 字段类型 | 字段说明 | 约束 |
---|---|---|---|
id | INT | 用户id | PRIMARY KEY、数设计AUTO_INCREMENT |
name | VARCHAR(50) | 用户名 | NOT NULL,据层 UNIQUE |
password | VARCHAR(50) | 用户密码 | NOT NULL |
state | ENUM(‘online’, ‘offline’) | 当前登录状态 | DEFAULT ‘offline’ |
对应着 MySQL 里的表字段设计,我们创建 User 类。数设计
#ifndef USER_H#define USER_H#include class User{public: User(int id = -1,据层 std::string name = "", std::string pwd = "", std::string state = "offline") : _id(id), _name(name), _state(state) {} void setId(const int &id) { _id = id; } void setName(const std::string &name) { _name = name; } void setPassword(const std::string &paw) { _password = paw; } void setState(const std::string &state) { _state = state; } int getId() { return _id; } std::string getName() { return _name; } std::string getPassword() { return _password; } std::string getState() { return _state; } protected: int _id; std::string _name; std::string _password; std::string _state; };#endif // USER_H
Model 层提供如下方法从操控 DB 层:
- 向 User 表插入一行
- 根据用户 ID 查询信息
- 更新某个用户的状态信息
- 重置用户的状态信息
#include "user.hpp"class UserModel{public: // User表的插入方法 bool insert(User &user); // 根据用户id查询用户信息 User query(int id); // 更新用户的状态信息 bool updateState(User user); // 重置用户的状态信息 void resetState();};
#include "usermodel.hpp"#include "db.h"#include bool UserModel::insert(User& user){ // 组装sql语句 char sql[1024] = ; snprintf(sql, sizeof(sql), "insert into user(name, password, state) values('%s', '%s', '%s')", user.getName().c_str(), user.getPassword().c_str(), user.getState().c_str()); MySQL mysql; if (mysql.connect()) { if (mysql.update(sql)) { user.setId(mysql_insert_id(mysql.getConnection())); return true; } } return false;}// 根据用户号码查询用户信息User UserModel::query(int id){ char sql[1024] = ; snprintf(sql, sizeof(sql), "select * from user where id = %d", id); MySQL mysql; if (mysql.connect()) { MYSQL_RES *res = mysql.query(sql); if (res != nullptr) { MYSQL_ROW row = mysql_fetch_row(res); if (row != nullptr) { // 生成一个User对象,填入信息 User user; user.setId(atoi(row[0])); user.setName(row[1]); user.setPassword(row[2]); user.setState(row[3]); mysql_free_result(res); return user; } } } // 返回空User return User();}bool UserModel::updateState(User user){ char sql[1024] = ; snprintf(sql,数设计 sizeof(sql), "update user set state = '%s' where id =%d", user.getState().c_str(), user.getId()); MySQL mysql; if (mysql.connect()) { if (mysql.update(sql)) { return true; } } return false;}// 重置用户的状态信息void UserModel::resetState(){ // 1.组装sql语句 char sql[1024] = "update user set state = 'offline' where state = 'online'"; MySQL mysql; if (mysql.connect()) { mysql.update(sql); }}
作者:热点