MySQL数据库表结构管理

MySQL数据库在游戏服务器领域应用很广泛。众所周知,MySQL是一种关系型数据库。一个MySQL数据库会由很多张表组成,而一张表又包括了最基本的表名,字段类型,字段名称等信息;非空表又是由很多条数据组成的,而每条数据又包含很多列,每一列又是包括字段名和字段值。那么怎么对上述信息进行管理,抽象出一组类来表示呢?

一、定义一个最基本的类来管理数据库表的最基本单元:字段,一个字段包括了字段类型和字段名称。

class Cell

{

public:

    Cell(int cell_type, const string& cell_name): _cell_type(cell_type), _cell_name(cell_name)

    {}

    ~Cell(){}

    int _cell_type; //字段类型

    string _cell_name; //字段名称

};

 

二、定义一个数据库表类,包含了多个上述字段

class Cells

{

public:

    vector<Cell*> _cells; //表中的字段

    string _cells_name; //表名

   

    Cells(){}

    explicit Cells(const string& cell_name) : _cells_name(cell_name){}

     virtual ~Cells();

     int size(); //表字段个数

     Cell* operator[](const string &name);//根据字段名获取一个表字段

     Cell* operator[](int pos); //根据位置获取一个表字段

     Cell* get_cell(int pos); //根据位置获取一个表字段

     bool add_cell(int cell_type, const string& cell_name); //往表里面加入一个字段

     bool add_cell(Cell *cell); //往表里面加入一个字段

     const char* get_cells_name() const //获取表名

     {

          return _cells_name.c_str();

     }

     void set_cells_name(const string& cells_name); //设置表名

};

 

三、定义管理数据库表类,用于管理所有的表。纯虚类,如果想使用这个类,需要继承它。

class CellsMgr

{

public:

    map<string, Cells*> _cellsmgr;

    static CellsMgr* get_instance();

    virtual bool init_all_cells(const string& url) = 0;//建立数据库连接等操作

    Cells* get_cells(const string& cell_name); //通过表名获取表结构

};

 

四、定义表记录类,包括字段名及值

class CellsRow

{

public:

    map<string, vector<uinsigned char> > _cells_row;

    template<typename T>

    void add_col_value(const char* cell_name, const T value);//给这条记录的某个字段添加一个值

};

 

五、定义管理表记录类,包括多个CellsRow

class CellsRows

{

public:

    vector<CellsRow*> _cells_rows;

    CellsRow* get_cells_row(int row); //获取某行记录

};

当初始化所有的数据库表后,通过这几个类提供的接口,就可以方便获取某张表的结构,获取表的字段,获取表的某一行记录等操作,从而实现了管理数据库表功能的需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值