Cplusplusplusplus首页投稿(暂停使用,暂停投稿)程序员

OCILIB 连接Oracle数据库——插入数据

2017-09-21  本文已影响445人  云谁之殇

二、进阶教程

参看官方文档实例,有详细的说明,包括:查询获取数据、绑定向量、数据库连接池、12c隐式结果集、使用Oracle对象和数据库通知等例子。这里只做一个最简单的插入数据演示。

1、简单的封装

void COciUtil::Init()
{
    CString strAppPath = CMyFileUtil::GetAppPathW();//获得程序运行目录
    ostring ociDllPath = CW2A(strAppPath);
    try
    {
        Environment::Initialize(Environment::Default,ociDllPath);
        }
    catch (std::exception& e)
    {
        CString text(e.what());
        AfxMessageBox(text);
    }
}

void COciUtil::Clean()
{
    try
    {
        conn.Close();
        Environment::Cleanup();
    }
    catch (std::exception& e)
    {
        CString text(e.what());
        AfxMessageBox(text);
    }
}

BOOL COciUtil::Connect(CString ip,int port,CString serviceName,CString username,CString password)
{
    try
    {
        CString strDB;
        strDB.Format(L"%s:%d/%s",ip,port,serviceName);
        char* db = CW2A(strDB);
        char* user = CW2A(username);
        char* pw = CW2A(password);
        conn.Open(db,user,pw);

        if (conn.IsNull())
            return FALSE;
        else
            return TRUE;
    }
    catch (std::exception& e)
    {
        CString text(e.what());
        AfxMessageBox(text);
        return FALSE;
    }
}

2、插入数据库

这里向数据库中插入数字、文本、时间、二进制。

BOOL COciDao::InsertTest()
{
    try
    {
        COciUtil oci;
        ocilib::Statement st(oci.conn);
        st.Prepare("insert into TEST(ID,TEXT,TIME,BIN) values ( :id , :text , :date , :blob )");
        
        int id = 123;
        char* binaryText = "eee向天歌浮绿水";
        ocilib::Blob blob(oci.conn);

        vector<BYTE> list;
        list.resize(strlen(binaryText));
        for (int i=0;i<strlen(binaryText);i++)
        {
            list.push_back(binaryText[i]);
        }
        blob.Write(list);

        ostring ostr = "texttexttext";
        COleDateTime time = COleDateTime::GetCurrentTime();
        ocilib::Date date = COleDateTime2Date(time);

        st.Bind<int>(":id",id,BindInfo::InOut);
        st.Bind<ostring,int>(":text",ostr,50,BindInfo::InOut);
        st.Bind<Date>(":date",date,BindInfo::InOut);
        st.Bind<Blob>(":blob",blob,BindInfo::InOut);

        st.ExecutePrepared();
        oci.conn.Commit();
        oci.Clean();
    }
    catch (std::exception &e) 
    {
        //cout<<e.what()<<endl;
        CString text(e.what());
        AfxMessageBox(text);
    }
}
上一篇下一篇

猜你喜欢

热点阅读