Model数据层代码框架设计
数据库的操作和业务代码分离开
在业务层看到对象,在数据库层看到数据库的操作。
我们要定义相关的一些类,和数据库的表一一对应的,才能把数据库读出来的字段合成一个对象提供给业务方去使用!
映射类!
我们在inlcude的server下创建一个文件夹:model
首先我们在model文件夹下创建文件:user.hpp
#ifndef USER_H
#define USER_H
#include <string>
using namespace std;
//User表的ORM类
class User
{
public:
User(int id = -1, string name = "", string pwd = "", string state = "offline")
{
this->id = id;
this->name = name;
this->password = pwd;
this->state = state;
}
//设置
void setId(int id) { this->id = id; }
void setName(string name) { this->name = name; }
void setPwd(string pwd) { this->password = pwd; }
void setState(string state) { this->state = state; }
//获取
int getId() { return this->id; }
string getName() { return this->name; }
string getPwd() { return this->password; }
string getState() { return this->state; }
protected:
int id;//ID号
string name;//姓名
string password;//密码
string state;//状态
};
#endif
我们在model文件夹下再创建文件:usermodel.hpp
#ifndef USERMODEL_H
#define USERMODEL_H
#include "user.hpp"
//User表的数据操作类
class UserModel {
public:
//User表的增加方法
bool insert(User &user);
//根据用户号码查询用户信息
User query(int id);
//更新用户的状态信息
bool updateState(User user);
//重置用户的状态信息
void resetState();
};
#endif
我们在src下的server下创建一个文件夹:model
在model下创建文件:usermodel.cpp
#include "usermodel.hpp"
#include "db.hpp"
#include <iostream>
using namespace std;
//User表的增加方法
bool UserModel::insert(User &user)
{
//1.组装sql语句
char sql[1024] = {0};
sprintf(sql, "insert into user(name, password, state) values('%s', '%s', '%s')",
user.getName().c_str(), user.getPwd().c_str(), user.getState().c_str());
MySQL mysql;//定义一个mysql对象
if (mysql.connect())//连接成功了
{
if (mysql.update(sql))//更新这个sql语句传进去
{
//获取插入成功的用户数据生成的主键id
user.setId(mysql_insert_id(mysql.getConnection()));//拿到数据库生成的id作为用户的id号
return true;
}
}
return false;
}