基于OCILIB的oracle数据库操作总结及自动生成Model和Dao的工具

基于OCILIB的oracle数据库操作总结

1.       类图

2.       基类BaseOCIDao的设计与实现

BaseOCIDao.h头文件

#pragma once

/* --------------------------------------------------------------------------------------------- *
 * INCLUDES
 * --------------------------------------------------------------------------------------------- */

#include "ocilib.h"
#include <string>
#include <vector>
using namespace std;
/* --------------------------------------------------------------------------------------------- *
 * PLATFORMS
 * --------------------------------------------------------------------------------------------- */

#ifdef _MSC_VER

  #if defined(OCI_CHARSET_WIDE)
      #pragma comment(lib, "ocilibw.lib")
  #elif defined(OCI_CHARSET_ANSI)
      #pragma comment(lib, "ociliba.lib")
  #endif

#endif

#ifndef OCI_SHARED_LIB
    #if defined(_WINDOWS)
        #define OCI_SHARED_LIB                   "oci.dll"
    #elif defined(__APPLE__)
        #define OCI_SHARED_LIB                   "libclntsh.dylib"
    #elif defined(__hppa)
        #define OCI_SHARED_LIB                   "libclntsh.sl"
    #else
        #define OCI_SHARED_LIB                   "libclntsh.so"
    #endif
#endif

#define print_frmt(f, x)    printf(f, x)
#define print_text(x)       printf(x)

#if defined(OCI_CHARSET_WIDE)
#ifdef _WINDOWS
#define print_ostr(x)   wprintf(OTEXT("%s"), x)
#else
#define print_ostr(x)   printf("%ls", x)
#endif
#else
#define print_ostr(x)   printf(OTEXT("%s"), x)
#endif

class BaseOCIDao
{
protected:
    string m_ip;
    unsigned int m_port;
    string m_inst;
    string m_user;
    string m_pwd;
    unsigned int m_mode;

    OCI_Statement* m_stmt;
    OCI_Connection* m_conn;

    bool m_useTrans;
    bool m_IsConnected;
    bool m_ShareConn;
    POCI_ERROR m_ErrHandler;
    vector<BaseOCIDao*> m_Children;
public:
    BaseOCIDao();
    BaseOCIDao(string ip,unsigned int port,string inst,string user,string pwd,POCI_ERROR ErrHandler,unsigned int mode=OCI_ENV_DEFAULT);
    virtual ~BaseOCIDao();

    BOOL Connect(BaseOCIDao* parent);
    BOOL AddChildDao(BaseOCIDao* child);

    BOOL Connect();
    BOOL DisConnect();

    OCI_Resultset* QuerySql(const char* sql);
    BOOL ExecuteSql(const char* sql);
    OCI_Statement* PrepareBindStmt(const char* sql);
    OCI_Resultset* QueryBindStmt(OCI_Statement *stmt);
    BOOL ExecuteBindStmt(OCI_Statement *stmt);

    BOOL BeginTrans();
    BOOL EndTrans();
    BOOL Commit();
    BOOL Rollback();
};

BaseOCIDao.cpp文件

#include "StdAfx.h"
#include "BaseOCIDao.h"

BaseOCIDao::BaseOCIDao(string ip,unsigned int port,string inst,string user,string pwd,POCI_ERROR ErrHandler,unsigned int mode)
{
    m_ip = ip;
    m_port = port;
    m_inst = inst;
    m_user = user;
    m_pwd = pwd;
    m_mode = mode;
    m_ErrHandler = ErrHandler;
    m_ShareConn = false;
    m_IsConnected = false;
    m_useTrans = false;

    m_stmt = NULL;
    m_conn = NULL;
}

BaseOCIDao::BaseOCIDao()
{
    m_ShareConn = false;
    m_IsConnected = false;
    m_useTrans = false;

    m_stmt = NULL;
    m_conn = NULL;
}

BaseOCIDao::~BaseOCIDao()
{
    if(m_IsConnected && !m_ShareConn)
        DisConnect();
}

BOOL BaseOCIDao::Connect(BaseOCIDao* parent)
{
    m_ShareConn = true;
    return TRUE;
}

BOOL BaseOCIDao::Connect()
{
    m_ShareConn = false;

    /* Possible values for parameter mode:
    * - OCI_ENV_DEFAULT  : default mode
    * - OCI_ENV_THREADED : multi-threading support
    * - OCI_ENV_CONTEXT  : thread contextual error handling
    * - OCI_ENV_EVENTS   : enables events for subscription, HA Events, AQ notifications
    */

    /* INITIALIZE OCI ------------------------------------------------------- */
    if (!OCI_Initialize(m_ErrHandler, NULL, m_mode))//the Oracle library is loaded from system environment variables
        return EXIT_FAILURE;

    OCI_EnableWarnings(TRUE);
    /* CONNECTION TO SERVER ------------------------------------------------- */
    char dbs[100];
    sprintf_s(dbs,100,"(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d)))(CONNECT_DATA=(SERVICE_NAME=%s)))",m_ip.c_str(),m_port,m_inst.c_str());
    m_conn = OCI_ConnectionCreate(dbs, m_user.c_str(), m_pwd.c_str(), OCI_SESSION_DEFAULT);
    if(m_conn!=NULL)
    {
        OCI_SetAutoCommit(m_conn,FALSE);
        m_IsConnected = true;

        for (vector<BaseOCIDao*>::iterator itr = m_Children.begin();
            itr!=m_Children.end(); itr++)
        {
            (*itr)->Connect(this);
        }

        return EXIT_SUCCESS;
    }
    else
    {
        print_ostr(OCI_ErrorGetString(OCI_GetLastError()));
        return EXIT_FAILURE;
    }
}

BOOL BaseOCIDao::DisConnect()
{
    if(m_conn!=NULL)
    {
        if(OCI_ConnectionFree(m_conn))
        {
            print_ostr(OCI_ErrorGetString(OCI_GetLastError()));
            OCI_Cleanup();
            return TRUE;
        }
        else
        {
            print_ostr(OCI_ErrorGetString(OCI_GetLastError()));
            return FALSE;
        }
    }
    else
        return FALSE;
}

BOOL BaseOCIDao::AddChildDao(BaseOCIDao* child)
{
    if(child!=NULL)
        m_Children.push_back(child);
    return TRUE;
}

OCI_Statement* BaseOCIDao::PrepareBindStmt(const char* sql)
{
    if(!m_IsConnected) return NULL;
    m_stmt = OCI_StatementCreate(m_conn);
    OCI_Prepare(m_stmt,sql);
    return m_stmt;
}

OCI_Resultset* BaseOCIDao::QuerySql(const char* sql)
{
    if(!m_IsConnected) return NULL;
    m_stmt = OCI_StatementCreate(m_conn);
    OCI_ExecuteStmt(m_stmt,sql);
    return OCI_GetResultset(m_stmt);
}

OCI_Resultset* BaseOCIDao::QueryBindStmt(OCI_Statement *stmt)
{
    if(!m_IsConnected) return NULL;
    OCI_Execute(stmt);
    return OCI_GetResultset(stmt);
}

BOOL BaseOCIDao::ExecuteSql(const char* sql)
{
    if(!m_IsConnected) return FALSE;
    m_stmt = OCI_StatementCreate(m_conn);
    BOOL flag = OCI_ExecuteStmt(m_stmt,sql);
    if(!m_useTrans && !m_ShareConn)
    {
        if(flag)
            OCI_Commit(m_conn);
        else
            OCI_Rollback(m_conn);
    }
    return flag;
}

BOOL BaseOCIDao::ExecuteBindStmt(OCI_Statement *stmt)
{
    if(!m_IsConnected) return FALSE;
    BOOL flag = OCI_Execute(stmt);
    if(!m_useTrans && !m_ShareConn)
    {
        if(flag)
            OCI_Commit(m_conn);
        else
            OCI_Rollback(m_conn);
    }
    return flag;
}

BOOL BaseOCIDao::BeginTrans()
{
    if(!m_IsConnected) return FALSE;
    m_useTrans = true;
    return TRUE;
}

BOOL BaseOCIDao::EndTrans()
{
    if(!m_IsConnected || !m_useTrans) return FALSE;
    m_useTrans = false;
    return TRUE;
}

BOOL BaseOCIDao::Commit()
{
    if(!m_IsConnected || !m_useTrans) return FALSE;
    return OCI_Commit(m_conn);
}

BOOL BaseOCIDao::Rollback()
{
    if(!m_IsConnected || !m_useTrans) return FALSE;
    return OCI_Rollback(m_conn);
}

3.       继承实体类的使用

3.1 BaseModel定义

BaseModel

#pragma once
#include <string>
using namespace std;
class BaseModel{
public:
    BaseModel(){}
    virtual ~BaseModel(){}
};

3.2 例子

Model定义

#pragma once

#include "BaseModel.h"
#include <string>
using namespace std;

#define NameSize 100
class TDao;
class TModel : BaseModel{
    friend TDao;
protected:
    int m_ID;
    char m_Name[NameSize];
public:
    TModel(){
        m_ID = 0;
        memset(m_Name,0,NameSize);
    }
    TModel(const TModel& obj)
    {
        m_ID = obj.GetID();
        SetName(obj.GetName());
    }

    TModel& operator = (const TModel& obj)
    {
        if(this == &obj) return *this;
        m_ID = obj.GetID();
        return *this;
    }
    ~TModel()
    {

    }

    void SetID(int ID)
    {
        m_ID = ID;
    }

    int GetID() const
    {
        return m_ID;
    }
    void SetName(string Name)
    {
        strcpy_s(m_Name,NameSize,Name.c_str());
    }

    string GetName() const
    {
        return m_Name;
    }
};

Dao定义

#include "BaseOCIDao.h"
class TDao:BaseOCIDao
{
public:
    TDao(){}
    TDao(string ip,unsigned int port,string inst,string user,string pwd,POCI_ERROR ErrHandler,unsigned int mode):
    BaseOCIDao(ip,port,inst,user,pwd,ErrHandler,mode)
    {

    }
    ~TDao(){}

    BOOL Insert(TModel* model)
    {
        char* sql = "insert into TabName(id,name) values (:id,:name)";
        OCI_Statement* stmt = PrepareBindStmt(sql);

        OCI_BindInt(stmt,":id",&model->m_ID);
        OCI_BindString(stmt,":name",model->m_Name,NameSize);
        return ExecuteBindStmt(stmt);
    }

    BOOL Update(TModel* model)
    {
        char* sql = "update TabName set name=:name where id=:id";
        OCI_Statement* stmt = PrepareBindStmt(sql);

        OCI_BindInt(stmt,":id",&model->m_ID);
        OCI_BindString(stmt,":name",model->m_Name,NameSize);
        return ExecuteBindStmt(stmt);
    }

    BOOL Delete(string cond)
    {
        string sql = "delete from TabName";
        if(cond!="")
            sql+=" where " + cond;

        return ExecuteSql(sql.c_str());
    }

    vector<TModel*> Select(string cond)
    {
        vector<TModel*> resVec;
        string sql = "select id,name from TabName";
        if(cond!="")
            sql+=" where " + cond;

        OCI_Resultset* rs = QuerySql(sql.c_str());
        while(OCI_FetchNext(rs))
        {
            TModel *model = new TModel();
            model->SetID(OCI_GetInt(rs,1));
            model->SetName(OCI_GetString(rs,2));
            resVec.push_back(model);
        }
        return resVec;
    }

    BOOL Exist(TModel* model)
    {
        char* sql = "select id from TabName where name=:name";
        OCI_Statement* stmt = PrepareBindStmt(sql);
        OCI_BindString(stmt,":name",model->m_Name,NameSize);
        OCI_Resultset* rs = QueryBindStmt(stmt);
        if(OCI_FetchNext(rs))
        {
            model->SetID(OCI_GetInt(rs,1));
            return TRUE;
        }
        else
            return FALSE;
    }
};

void err_handler(OCI_Error *err)
{
    int err_type = OCI_ErrorGetType(err);

    print_text("\n");

    if (err_type == OCI_ERR_WARNING)
    {
        print_text("> WARNING : ");
    }
    else
    {
        print_text("> ERROR   : ");
    }

    print_ostr(OCI_ErrorGetString(err));
    print_text("\n");
}

DaoFactory定义

class DaoFactory{
private:
    string m_ip;
    unsigned int m_port;
    string m_inst;
    string m_user;
    string m_pwd;
    unsigned int m_mode;
private:
    DaoFactory(){
        m_ip = "127.0.0.1";
        m_port = 1521;
        m_inst = "orcl";
        m_user = "user";
        m_pwd = "password";
        m_mode = OCI_ENV_DEFAULT;
    }
public:
    static DaoFactory* GetInstance()
    {
        static DaoFactory factory;
        return &factory;
    }
    ~DaoFactory(){}
public:
    TDao* CreateTDao()
    {
        TDao* dao = new TDao(m_ip,m_port,m_inst,m_user,m_pwd,err_handler,m_mode);
        return dao;
    }
};

简单情况

  1. 创建dao对象 dao
  2. 打开数据库连接 dao->Connect
  3. 执行搜索或增删改操作 dao->Select dao->Insert ….
  4. 关闭数据库连接 dao->DisConnect
  5. 删除dao对象 delete dao;
  6. 创建两个dao对象:DaoParent, DaoChild;
  7. DaoParent->AddChildDao(DaoChild);
  8. 打开数据库连接DaoParent->Connect();
  9. 搜索 DaoParent->Select();DaoChild->Select();
  10. 关闭数据库连接 DaoParent->DisConnect();
  11. 删除dao对象内存;delete DaoChild; delete DaoParent;
  12. 创建两个dao对象:DaoParent, DaoChild;
  13. DaoParent->AddChildDao(DaoChild);
  14. 打开数据库连接DaoParent->Connect();
  15. 打开事务 DaoParent-> BeginTrans
  16. 执行增删改操作 DaoParent->Insert();DaoChild->Update();。。。
  17. 提交或回滚事务 DaoParent-> Commit DaoParent-> Rollback
  18. 关闭事务 DaoParent-> EndTrans
  19. 关闭数据库连接 DaoParent->DisConnect();
  20. 删除dao对象内存;delete DaoChild; delete DaoParent;

更复杂的情况

共享数据库连接进行查询

  1. 创建两个dao对象:DaoParent, DaoChild;
  2. DaoParent->AddChildDao(DaoChild);
  3. 打开数据库连接DaoParent->Connect();
  4. 搜索 DaoParent->Select();DaoChild->Select();
  5. 关闭数据库连接 DaoParent->DisConnect();
  6. 删除dao对象内存;delete DaoChild; delete DaoParent;

共享数据库事务,进行增删改操作

  1. 创建两个dao对象:DaoParent, DaoChild;
  2. DaoParent->AddChildDao(DaoChild);
  3. 打开数据库连接DaoParent->Connect();
  4. 打开事务 DaoParent-> BeginTrans
  5. 执行增删改操作 DaoParent->Insert();DaoChild->Update();。。。
  6. 提交或回滚事务 DaoParent-> Commit DaoParent-> Rollback
  7. 关闭事务 DaoParent-> EndTrans
  8. 关闭数据库连接 DaoParent->DisConnect();
  9. 删除dao对象内存;delete DaoChild; delete DaoParent;

4.       自动生成Model和Dao的工具设计

工具从输入流中读入一组规定格式的数据,按照此数据构建Model和Dao类代码。

输入内容格式规定

类名

数据库表名

字段个数N

字段1 类型1 数据库字段名1

字段N 类型N 数据库字段名N

支持的类型


类型


真实类型


数据库对应类型


int


int


number(10)


unsigned int


unsigned int


number(10)


short


short


number(5)


unsigned short


unsigned short


number(5)


float


float


binary_float


double


double


binary_double


string


char[]


varchar2()


big_int


long long


number(14)


big_uint


unsigned long long


number(14)

例子:

User类有3个字段,IDNamePwd

可输入如下:

User

UserTable

3

ID unsigned int ID

Name string Name

Pwd string Pwd

自动生成工具根据BaseMode和BaseOCIDao生成,可根据需要将生成后的Model和Dao进行修改。对于stirng类型的数据,自动生成Model后,可修改xxxSize宏,设置string类型字段的长度。

自动生成Model和Dao的工具AutoGenModelDao

AutoGenModelDao.h

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

typedef struct FieldType
{
    string Field;
    string FType;//string,int,unsigned int, short,unsigned short,float,double,big_int,big_uint
    string DBField;
    friend istream& operator >> (istream& myin,FieldType& obj)
    {
        myin>>obj.Field;
        myin>>obj.FType;
        if(obj.FType=="unsigned")
        {
            string tmp;
            myin>>tmp;
            obj.FType = obj.FType+" "+tmp;
        }
        myin>>obj.DBField;
        return myin;
    }
}FieldType;

class AutoGenModelDao
{
private:
    string m_ModelClass;
    string m_DaoClass;
    string m_DBTable;
    string m_OutputDir;
    vector<FieldType> m_Fields;
public:
    AutoGenModelDao();
    ~AutoGenModelDao();

    void AutoGen(istream& myin);
private:
    void GenModelHeader();
    ostream& GenConstructFun(ostream& myout);
    ostream& GenGetSetFun(ostream& myout);
    void GenModelBody();
private:
    void GenDaoHeader();
    void GenDaoBody();
    ostream& GenInsertFun(ostream& myout);
    ostream& GenUpdateFun(ostream& myout);
    ostream& GenDeleteFun(ostream& myout);
    ostream& GenSelectFun(ostream& myout);
    ostream& GenExistFun(ostream& myout);
};

AutoGenModelDao.cpp

#include "StdAfx.h"
#include "AutoGenModelDao.h"
#include <iostream>
#include <fstream>
using namespace std;

AutoGenModelDao::AutoGenModelDao(void)
{
}

AutoGenModelDao::~AutoGenModelDao(void)
{
}

void AutoGenModelDao::AutoGen(istream& myin)
{
    m_OutputDir = "..\\output";
    string className;
    myin>>className;//ClassName
    m_ModelClass = className+"Model";
    m_DaoClass = className+"Dao";
    myin>>m_DBTable;
    int fieldLen;
    myin>>fieldLen;
    m_Fields.clear();
    for (int i=0;i<fieldLen;i++)
    {
        FieldType field;
        myin>>field;
        m_Fields.push_back(field);
    }

    GenModelHeader();
    GenModelBody();
    GenDaoHeader();
    GenDaoBody();
}

void AutoGenModelDao::GenModelHeader()
{
    int strsize = 100;
    string file = m_OutputDir+"\\"+m_ModelClass+".h";
    ofstream myout(file.c_str(),ios::out);
    myout<<"#pragma once"<<endl;
    myout<<"#include \"BaseModel.h\""<<endl;
    myout<<"#include <string>"<<endl;
    myout<<"using namespace std;"<<endl;

    myout<<endl;
    //build #define string size
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType == "string")
            myout<<"#define "<<itr->Field<<"Size "<<strsize<<endl;
    }
    myout<<endl;
    myout<<"class "<<m_DaoClass<<";"<<endl;
    myout<<"class "<<m_ModelClass<<" : BaseModel{"<<endl;
    myout<<"friend "<<m_DaoClass<<";"<<endl;

    myout<<"protected:"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType == "string")
            myout<<"\t    char m_"<<itr->Field<<"["<<itr->Field<<"Size];"<<endl;
        else
            myout<<"\t    "<<itr->FType<<" m_"<<itr->Field<<";"<<endl;
    }
    myout<<endl;

    myout<<"public:"<<endl;
    myout<<"\t    "<<m_ModelClass<<"();"<<endl;
    myout<<"\t    ~"<<m_ModelClass<<"();"<<endl;
    myout<<"\t    "<<m_ModelClass<<"(const "<<m_ModelClass<<"& obj);"<<endl;
    myout<<"\t    "<<m_ModelClass<<"& operator = (const "<<m_ModelClass<<"& obj);"<<endl;

    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        myout<<"\t    void Set"<<itr->Field<<"("<<itr->FType<<" val);"<<endl;
        myout<<"\t    "<<itr->FType<<" Get"<<itr->Field<<"() const;"<<endl;
    }

    myout<<"};"<<endl;
    myout.close();
}

void AutoGenModelDao::GenModelBody()
{
    string file = m_OutputDir+"\\"+m_ModelClass+".cpp";
    ofstream myout(file.c_str(),ios::out);
    myout<<"#include \"StdAfx.h\""<<endl;
    myout<<"#include \""<<m_ModelClass<<".h\""<<endl;
    GenConstructFun(myout);
    GenGetSetFun(myout);
    myout.close();
}
ostream& AutoGenModelDao::GenConstructFun(ostream& myout)
{
    myout<<m_ModelClass<<"::"<<m_ModelClass<<"(){"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType!="string")
            myout<<"\t    m_"<<itr->Field<<" = 0;"<<endl;
    }
    myout<<"}"<<endl;
    myout<<endl;
    myout<<m_ModelClass<<"::~"<<m_ModelClass<<"(){}"<<endl;
    myout<<endl;
    myout<<m_ModelClass<<"::"<<m_ModelClass<<"(const "<<m_ModelClass<<"& obj){"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType!="string")
            myout<<"\t    m_"<<itr->Field<<" = obj.Get"<<itr->Field<<"();"<<endl;
        else
            myout<<"\t    Set"<<itr->Field<<"(obj.Get"<<itr->Field<<"());"<<endl;
    }
    myout<<"}"<<endl;
    myout<<endl;
    myout<<m_ModelClass<<"& "<<m_ModelClass<<"::operator = (const "<<m_ModelClass<<"& obj){"<<endl;
    myout<<"\t    if(this == &obj) return *this;"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType!="string")
            myout<<"\t    m_"<<itr->Field<<" = obj.Get"<<itr->Field<<"();"<<endl;
        else
            myout<<"\t    Set"<<itr->Field<<"(obj.Get"<<itr->Field<<"());"<<endl;
    }
    myout<<"\t    return *this;"<<endl;
    myout<<"}"<<endl;
    return myout;
}
ostream& AutoGenModelDao::GenGetSetFun(ostream& myout)
{
    myout<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        myout<<"void "<<m_ModelClass<<"::Set"<<itr->Field<<"("<<itr->FType<<" val){"<<endl;
        if(itr->FType != "string")
            myout<<"\t    m_"<<itr->Field<<" = val;"<<endl;
        else
            myout<<"\t    strcpy_s(m_"<<itr->Field<<","<<itr->Field<<"Size,val.c_str());"<<endl;
        myout<<"}"<<endl;
        myout<<endl;

        myout<<itr->FType<<" "<<m_ModelClass<<"::Get"<<itr->Field<<"()const{"<<endl;
        myout<<"\t    return m_"<<itr->Field<<";"<<endl;
        myout<<"}"<<endl;
    }
    return myout;
}
void AutoGenModelDao::GenDaoHeader()
{
    string file = m_OutputDir+"\\"+m_DaoClass+".h";
    ofstream myout(file.c_str(),ios::out);
    myout<<"#pragma once"<<endl;
    myout<<"#include \""<<m_ModelClass<<".h\""<<endl;
    myout<<"#include \"BaseOCIDao.h\""<<endl;
    myout<<"#include <string>"<<endl;
    myout<<"#include <vector>"<<endl;
    myout<<"using namespace std;"<<endl;
    myout<<endl;
    myout<<"class "<<m_DaoClass<<" : BaseOCIDao{"<<endl;
    myout<<"public:"<<endl;
    myout<<"\t    "<<m_DaoClass<<"():BaseOCIDao(){}"<<endl;
    myout<<"\t    "<<m_DaoClass<<"(string ip,unsigned int port,string inst,string user,string pwd,POCI_ERROR ErrHandler,unsigned int mode):BaseOCIDao(ip,port,inst,user,pwd,ErrHandler,mode){}"<<endl;
    myout<<"\t    ~"<<m_DaoClass<<"(){}"<<endl;
    myout<<"\t    BOOL Insert("<<m_ModelClass<<"* model);"<<endl;
    myout<<"\t    BOOL Update("<<m_ModelClass<<"* model);"<<endl;
    myout<<"\t    BOOL Exist("<<m_ModelClass<<"* model);"<<endl;
    myout<<"\t    BOOL Delete(string cond);"<<endl;
    myout<<"\t    vector<"<<m_ModelClass<<"*> Select(string cond);"<<endl;
    myout<<"};"<<endl;
    myout.close();
}

void AutoGenModelDao::GenDaoBody()
{
    string file = m_OutputDir+"\\"+m_DaoClass+".cpp";
    ofstream myout(file.c_str(),ios::out);
    myout<<"#include \"StdAfx.h\""<<endl;
    myout<<"#include \""<<m_ModelClass<<".h\""<<endl;
    myout<<"#include \""<<m_DaoClass<<".h\""<<endl;
    myout<<endl;
    GenInsertFun(myout);
    GenUpdateFun(myout);
    GenDeleteFun(myout);
    GenSelectFun(myout);
    GenExistFun(myout);
    myout.close();
}
ostream& AutoGenModelDao::GenInsertFun(ostream& myout)
{
    myout<<endl;
    myout<<"BOOL "<<m_DaoClass<<"::Insert("<<m_ModelClass<<"* model){"<<endl;
    myout<<"\t    char* sql=\"insert into "<<m_DBTable<<"(";
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        myout<<itr->DBField;
        if(itr+1 != m_Fields.end())
            myout<<",";
    }
    myout<<") values (";
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        myout<<":"<<itr->Field;
        if(itr+1 != m_Fields.end())
            myout<<",";
    }
    myout<<")\";"<<endl;
    myout<<endl;

    myout<<"\t    OCI_Statement* stmt = PrepareBindStmt(sql);"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType=="int")
            myout<<"\t    OCI_BindInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned int")
            myout<<"\t    OCI_BindUnsignedInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "short")
            myout<<"\t    OCI_BindShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned short")
            myout<<"\t    OCI_BindUnsignedShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "float")
            myout<<"\t    OCI_BindFloat(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "double")
            myout<<"\t    OCI_BindDouble(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_int")
            myout<<"\t    OCI_BindBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_uint")
            myout<<"\t    OCI_BindUnsignedBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "string")
            myout<<"\t    OCI_BindString(stmt,\":"<<itr->Field<<"\",model->m_"<<itr->Field<<","<<itr->Field<<"Size);"<<endl;
    }
    myout<<"\t    return ExecuteBindStmt(stmt);"<<endl;
    myout<<"}"<<endl;
    return myout;
}
ostream& AutoGenModelDao::GenUpdateFun(ostream& myout)
{
    myout<<endl;
    myout<<"BOOL "<<m_DaoClass<<"::Update("<<m_ModelClass<<"* model){"<<endl;
    myout<<"\t    char* sql=\"update "<<m_DBTable<<" set ";
    vector<FieldType>::iterator itr = m_Fields.begin();
    itr++;
    for (;itr != m_Fields.end(); itr++)
    {
        myout<<itr->DBField<<" = :"<<itr->Field;
        if(itr+1 != m_Fields.end())
            myout<<",";
    }
    myout<<" where "<<m_Fields.begin()->DBField<<"=:"<<m_Fields.begin()->Field<<"\";"<<endl;
    myout<<endl;

    myout<<"\t    OCI_Statement* stmt = PrepareBindStmt(sql);"<<endl;
    for (vector<FieldType>::iterator itr = m_Fields.begin();
        itr != m_Fields.end(); itr++)
    {
        if(itr->FType=="int")
            myout<<"\t    OCI_BindInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned int")
            myout<<"\t    OCI_BindUnsignedInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "short")
            myout<<"\t    OCI_BindShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned short")
            myout<<"\t    OCI_BindUnsignedShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "float")
            myout<<"\t    OCI_BindFloat(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "double")
            myout<<"\t    OCI_BindDouble(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_int")
            myout<<"\t    OCI_BindBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_uint")
            myout<<"\t    OCI_BindUnsignedBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "string")
            myout<<"\t    OCI_BindString(stmt,\":"<<itr->Field<<"\",model->m_"<<itr->Field<<","<<itr->Field<<"Size);"<<endl;
    }
    myout<<"\t    return ExecuteBindStmt(stmt);"<<endl;
    myout<<"}"<<endl;
    return myout;
}
ostream& AutoGenModelDao::GenDeleteFun(ostream& myout)
{
    myout<<endl;
    myout<<"BOOL "<<m_DaoClass<<"::Delete(string cond){"<<endl;
    myout<<"\t    string sql=\"delete from "<<m_DBTable<<"\";"<<endl;
    myout<<"\t    if(cond!=\"\") sql+=\" where \"+cond;"<<endl;
    myout<<"\t    return ExecuteSql(sql.c_str());"<<endl;
    myout<<"}"<<endl;
    return myout;
}
ostream& AutoGenModelDao::GenSelectFun(ostream& myout)
{
    myout<<endl;
    myout<<"vector<"<<m_ModelClass<<"*> "<<m_DaoClass<<"::Select(string cond){"<<endl;
    myout<<"\t    vector<"<<m_ModelClass<<"*> resVec;"<<endl;
    myout<<"\t    string sql=\"select ";
    vector<FieldType>::iterator itr = m_Fields.begin();
    for (;itr != m_Fields.end(); itr++)
    {
        myout<<itr->DBField;
        if(itr+1 != m_Fields.end())
            myout<<",";
    }
    myout<<" from "<<m_DBTable<<"\";"<<endl;
    myout<<"\t    if(cond!=\"\") sql+=\" where \"+cond;"<<endl;
    myout<<"\t    OCI_Resultset* rs = QuerySql(sql.c_str());"<<endl;
    myout<<"\t    while(OCI_FetchNext(rs)){"<<endl;
    myout<<"\t        "<<m_ModelClass<<"* model = new "<<m_ModelClass<<"();"<<endl;

    int fieldCnt = 0;
    for (itr=m_Fields.begin();itr != m_Fields.end(); itr++)
    {
        fieldCnt++;
        myout<<"\t        model->Set"<<itr->Field<<"(";
        if(itr->FType=="int")
            myout<<"OCI_GetInt(rs,"<<fieldCnt<<")";
        else if(itr->FType == "unsigned int")
            myout<<"OCI_GetUnsignedInt(rs,"<<fieldCnt<<")";
        else if(itr->FType == "short")
            myout<<"OCI_BindShort(rs,"<<fieldCnt<<")";
        else if(itr->FType == "unsigned short")
            myout<<"OCI_GetUnsignedShort(rs,"<<fieldCnt<<")";
        else if(itr->FType == "float")
            myout<<"OCI_GetFloat(rs,"<<fieldCnt<<")";
        else if(itr->FType == "double")
            myout<<"OCI_BindDouble(rs,"<<fieldCnt<<")";
        else if(itr->FType == "big_int")
            myout<<"OCI_GetBigInt(rs,"<<fieldCnt<<")";
        else if(itr->FType == "big_uint")
            myout<<"OCI_GetUnsignedBigInt(rs,"<<fieldCnt<<")";
        else if(itr->FType == "string")
            myout<<"OCI_GetString(rs,"<<fieldCnt<<")";

        myout<<");"<<endl;
    }
    myout<<"\t        resVec.push_back(model);"<<endl;
    myout<<"\t    }"<<endl;
    myout<<"\t    return resVec;"<<endl;
    myout<<"}"<<endl;
    return myout;
}
ostream& AutoGenModelDao::GenExistFun(ostream& myout)
{
    myout<<endl;
    myout<<"BOOL "<<m_DaoClass<<"::Exist("<<m_ModelClass<<"* model){"<<endl;
    vector<FieldType>::iterator itr = m_Fields.begin();
    myout<<"\t    char* sql=\"select "<<itr->DBField<<" from "<<m_DBTable<<" where ";
    itr++;
    for (;itr != m_Fields.end(); itr++)
    {
        myout<<itr->DBField<<" = :"<<itr->Field;
        if(itr+1 != m_Fields.end())
            myout<<",";
    }
    myout<<"\";"<<endl;

    myout<<"\t    OCI_Statement* stmt = PrepareBindStmt(sql);"<<endl;
    itr = m_Fields.begin();
    itr++;
    for (;itr != m_Fields.end(); itr++)
    {
        if(itr->FType=="int")
            myout<<"\t    OCI_BindInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned int")
            myout<<"\t    OCI_BindUnsignedInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "short")
            myout<<"\t    OCI_BindShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "unsigned short")
            myout<<"\t    OCI_BindUnsignedShort(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "float")
            myout<<"\t    OCI_BindFloat(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "double")
            myout<<"\t    OCI_BindDouble(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_int")
            myout<<"\t    OCI_BindBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "big_uint")
            myout<<"\t    OCI_BindUnsignedBigInt(stmt,\":"<<itr->Field<<"\",&model->m_"<<itr->Field<<");"<<endl;
        else if(itr->FType == "string")
            myout<<"\t    OCI_BindString(stmt,\":"<<itr->Field<<"\",model->m_"<<itr->Field<<","<<itr->Field<<"Size);"<<endl;
    }
    myout<<"\t    OCI_Resultset* rs = QueryBindStmt(stmt);"<<endl;
    myout<<"\t    if(OCI_FetchNext(rs)){"<<endl;
    myout<<"\t        model->Set"<<m_Fields.begin()->Field<<"(OCI_GetUnsignedInt(rs,1));"<<endl;
    myout<<"\t        return TRUE;"<<endl;
    myout<<"\t    }"<<endl;
    myout<<"\t    else return FALSE;"<<endl;
    myout<<"}"<<endl;
    return myout;
}

点我下载上述例子及自动生成Model和Dao的代码

时间: 2024-10-07 08:52:53

基于OCILIB的oracle数据库操作总结及自动生成Model和Dao的工具的相关文章

查询ORACLE数据库操作记录

代码: SELECT a.First_Load_Time,        a.Sql_Text,        s.Sid,        s.Serial#,        s.Program --,        ,        a.* --       Utl_Inaddr.Get_Host_Address(s.Terminal) Ip   FROM V$sqlarea a, V$session s  WHERE s.Sql_Address(+) = a.Address    AND U

C# Oracle数据库操作类实例详解

本文所述为C#实现的Oracle数据库操作类,可执行超多常用的Oracle数据库操作,包含了基础数据库连接.关闭连接.输出记录集.执行Sql语句,返回带分页功能的dataset .取表里字段的类型和长度等,同时还有哈稀表自动插入数据库等高级任务.需要特别指出的是:在执行SQL语句,返回 DataReader之前一定要先用.read()打开,然后才能读到数据,再用hashTable对数据库进行insert,update,del操作,注意此时只能用默认的数据库连接"connstr". 本文

oracle数据库操作语句

常用到的oracle数据库操作语句,以下仅供参考: 一. 查询 1.查询某个数据库表大于某个日期的所有数据条数    select count(*) from ALARM_LOG t where t.ALARM_START_TIME> to_date('2017-01-10 08:00:00','yyyy-mm-dd hh24:mi:ss');   查询某个数据库表大于某个日期的所有历史数据  select * from ALARM_LOG t where t.ALARM_START_TIME>

(转)C# Oracle数据库操作类

原文地址:http://www.cnblogs.com/haibing0107/p/6143922.html using System;using System.Data;using System.Collections.Generic;using System.Configuration;using System.Data.OracleClient;using System.Text;using System.IO; /// <summary>  /// Oracle数据库操作类  ///

Oracle数据库操作知道

SELECT TGTID,PHONENUM,REGISTERDATE ,to_date(REGISTERDATE,'YYYY-MM-DD HH24:MI:SS') AS T FROM WTRESSENWEB.T_AXMALL_COMMONCLIENT WHERE TGTID = '2087' AND to_date(REGISTERDATE,'YYYY-MM-DD HH24:MI:SS') > to_date('2014-07-09','yyyy-mm-dd'); 对于to_char() to_

oracle中利用trigger,sequence自动生成ID

http://zhanghong.iteye.com/blog/865937 1. 首先创建数据库表 SQL> create table customer( 2  id number(8) not null primary key, 3  name varchar2(20), 4  age number(3), 5  gender varchar2(8) 6  ); 2. 创建Sequence: create sequence customer_SEQUENCE start with 6 inc

oracle数据库 操作clob对象

clob类型,但对于这个类型处理起来还是比较麻烦的,varchar2长度为4000bytes,如果varchar2能满足楼主的需求,建议使用varchar2,下面提供了在Java 中读取clob类型的方式,我主要讲的是JDBC的操作,Hibernate目前不讲,操作这个Clob列主要分为插入和获取俩个操作:1.Java程序插入Clob值到Oracle数据库表中:   String clob= "这里主要是要插入到表中的值";     //前面具体数据库连接代码这里省略,直接进正题  

Python实战之Oracle数据库操作

1. 要想使Python可以操作Oracle数据库,首先需要安装cx_Oracle包,可以通过下面的地址来获取安装包 [plain] view plain copy http://cx-oracle.sourceforge.net/ 2. 另外还需要oracle的一些类库,此时需要在运行python的机器上安装Oracle Instant Client软件包,可以通过下面地址获得 [plain] view plain copy http://www.oracle.com/technetwork/

Oracle 数据库操作

---恢复内容开始--- 现在大型企业一般都用Oracle数据库,Oracle数据库在一般采用expdp,impdp 导出导入数据,但是在操作中经常会遇到一些问题.下面来浅析这些问题. 1. 导出数据 一般导出数据的时候需要建立一个目录地址 select * from dba_directories; --查询所有目录地址create or replace directory winqt_dump as '/home/front/dmpfile'; --创建目录地址grant read,writ