CORMBase解决的是实体记录到对象的双向操作问题.绑定到一个固定的表上.
如CORMBase的Load方法查询的字段全部来自该表。
对于跨表查询无法支持。
早期的在查询函数中声明绑定器,逐个查询列进行绑定可以实现.
但代码结构欠佳,并且每次调用都要构造对象和绑定,影响性能.
增加基础类CQuerier(通用查询器)类模板,简化查询处理.
把查询结果按对象处理.
1.CQuerier
//////////////////////////////////////////////////////////////////////////////// #define QUERY_BIND_DECLARE_BEGIN(CLS) \ CRecordsetBindObject<CLS> CLS::binder_; \ bool CLS::init_flag_ = false; \ CFieldBind CLS::fld_bind_[] = { #define QUERY_BIND_DECLARE_END(CLS) \ };\ short CLS::fld_bind_num_ = sizeof(CLS::fld_bind_)/sizeof(CFieldBind); //////////////////////////////////////////////////////////////////////////////// #define QUERY_BIND_DEFINE(CLS) \ public:\ static CFieldBind fld_bind_[];\ static short fld_bind_num_;\ static bool init_flag_; \ static CRecordsetBindObject<CLS> binder_; \ static int InitBinder() { \ if (init_flag_) \ return 0; \ binder_.SetFieldBindInfo(&fld_bind_[0],fld_bind_num_,false);\ init_flag_ = true;\ return 0;\ } //////////////////////////////////////////////////////////////////////////////// ///< 查询器 ///< 在指定的连接上执行执行的SQL,把结果生成查询结果对象 template <class T> class CQuerier { string dbc_name_; ///< 连接名 public: CQuerier(const char *dbc_name):dbc_name_(dbc_name) { } int Query(const char *sql,vector<T*> &data); ///< 执行查询命令,结果对象保存在data中. };
2.使用示例
1.定义查询结果对象示例类,在数据对象定义.H文件中.
///< 查询结果对象示例类 class CQueryResultTest { public: ///< 查询结果成员变量 unsigned int eid_; unsigned int sheet_id_; string goods_name_; public: QUERY_BIND_DEFINE(CQueryResultTest) };
2.绑定声明,在cpp文件中.
///< 定义绑定关系 QUERY_BIND_DECLARE_BEGIN(CQueryResultTest) FIELD_BIND1(CQueryResultTest,sheet_id_,"SheetID"), FIELD_BIND1(CQueryResultTest,eid_,"EId"), FIELD_BIND1(CQueryResultTest,goods_name_,"GoodsName"), QUERY_BIND_DECLARE_END(CQueryResultTest)
3.使用
///< 一个测试函数 int CPOS::Test() { string sql = "select *,b.GoodsName from t_pos_SaleDetail a, t_Bas_ShopGoods b " "where a.Eid=b.EId and a.Goodsid=b.GoodsID and a.Eid=11000001 and a.Posid=1 and a.Sheetid=1"; CQuerier<CQueryResultTest> querier(this->local_dbc_.c_str()); ///< 声明QueryResultTest为模板参数的查询器,使用指定的连接 CAutoVector<CQueryResultTest*> v_data; int ret = querier.Query(sql.c_str(),v_data); ///< 执行查询,成功时对象保存在v_data中. return 0; }