开源项目之Oracle驱动 OCILIB

OCILIB是一个便携式Oracle驱动程序,可提供非常快速和可靠地访问Oracle数据库。它提供了一个丰富,功能齐全,并易于使用的API 。OCILIB 支持运行的所有Oracle平台。

主要的功能包括:提供了丰富的,功能齐全且易于使用的API 、运行在所有Oracle平台是用纯的ISO C代码与本地的ISO ç Unicode支持OCI封装(甲骨文调用接口) 是最完整的可保监包装

工程如图:

开源项目之Oracle驱动 OCILIB_第1张图片

测试主要代码:

int mtmain(int argc, mtarg* argv[])
{
    mtext home[SIZE_STR+1] = MT("");
    mtext dbs [SIZE_STR+1] = MT("");
    mtext usr [SIZE_STR+1] = MT("");
    mtext pwd [SIZE_STR+1] = MT("");

    size_t i;

	//模拟参数
	argc = 5;
	argv[0] = "";
	argv[1] = "";
	argv[2] = "";
	argv[3] = "";
	argv[4] = "";

    /* CHECK COMMAND LINE --------------------------------------------------- */

    if (argc < (ARG_COUNT-1))
    {
        return EXIT_FAILURE;
    }

    /* GET ARGUMENTS ---------------------------------------------------------*/

    GET_ARG(dbs, ARG_DB);
    GET_ARG(usr, ARG_USER);
    GET_ARG(pwd, ARG_PWD);

    if(argc == ARG_COUNT)
        GET_ARG(home, ARG_HOME);

    /* INITIALIZE OCI ------------------------------------------------------- */

	//初始化操作
    if (!OCI_Initialize(err_handler, home, OCI_ENV_DEFAULT))
        return EXIT_FAILURE;

    OCI_EnableWarnings(TRUE);

    /* CONNECTION TO SERVER ------------------------------------------------- */

    print_text("Connecting to ");
    print_args(usr);
    print_text("/");
    print_args(pwd);
    print_text("@");
    print_args(dbs);
    print_text("\n\n");

	//创建连接
    cn = OCI_ConnectionCreate(dbs, usr, pwd, OCI_SESSION_DEFAULT);

    if (cn)
    {
		//声明
        st = OCI_StatementCreate(cn);

		//输出版本
        print_version();

		//创建表
        create_tables();

        /* execute tests */

        for (i = 0; i < ARRAY_COUNT(tab_test); i++)
        {
			//执行语句
            if (tab_test[i].execute)
                tab_test[i].proc();
        }

		//删表
        drop_tables();

		//断开
        disconnect();
    }
    else
    {
        print_mstr(OCI_ErrorGetString(OCI_GetLastError()));
    }

	//释放资源
    cleanup();

    print_text("\npress any key to exit...");

    getchar();

    return EXIT_SUCCESS;
}

//错误处理函数
void err_handler(OCI_Error *err)
{
    int err_type = OCI_ErrorGetType(err);

    print_text("\n");

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

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

//清除
void cleanup(void)
{
    OCI_Cleanup();

    print_frmt("\n%i errors   \n", nb_err);
    print_frmt("\n%i warnings \n\n", nb_warn);
}

//断开 释放资源
void disconnect(void)
{
    OCI_ConnectionFree(cn);
}

//输出版本信息
void print_version(void)
{
    print_text("\n>>>>> OCILIB BUILD INFORMATION \n\n");

    if (OCI_GetImportMode() == OCI_IMPORT_MODE_LINKAGE)
        print_text("OCI import mode         : LINKAGE\n");
    else
        print_text("OCI import mode         : RUNTIME\n");

    if (OCI_GetCharsetMetaData() == OCI_CHAR_ANSI)
        print_text("MetaData  char type     : ANSI\n");
    else
        print_text("MetaData  char type     : WIDE\n");

    if (OCI_GetCharsetUserData() == OCI_CHAR_ANSI)
        print_text("UserData  char type     : ANSI\n");
    else
        print_text("UserData  char type     : WIDE\n");

    print_text("\n>>>>> VERSIONS INFORMATION \n\n");

    print_frmt("OCILIB major    version : %i\n",   OCILIB_MAJOR_VERSION);
    print_frmt("OCILIB minor    version : %i\n",   OCILIB_MINOR_VERSION);
    print_frmt("OCILIB revision version : %i\n\n", OCILIB_REVISION_VERSION);

    /* print all versions */
    print_frmt("OCI compile     version : %i\n",   OCI_VER_MAJ(OCI_GetOCICompileVersion()));
    print_frmt("OCI runtime     version : %i\n\n", OCI_VER_MAJ(OCI_GetOCIRuntimeVersion()));

    print_frmt("Server major    version : %i\n",   OCI_GetServerMajorVersion(cn));
    print_frmt("Server minor    version : %i\n",   OCI_GetServerMinorVersion(cn));
    print_frmt("Server revision version : %i\n\n", OCI_GetServerRevisionVersion(cn));

    print_frmt("Connection      version : %i\n\n", OCI_GetVersionConnection(cn));

    print_text("\n>>>>> SERVER VERSION BANNER \n\n");

    /* print server string version */

    print_mstr(OCI_GetVersionServer(cn));

    print_text("\n\n");

}

//创建表
void create_tables(void)
{
    print_text("\n>>>>> CREATE TABLES FOR DEMO \n\n");

    /* create types for the demo */
    OCI_ExecuteStmt(st, MT("create type type_t as OBJECT (id int, name varchar2(50))"));

    OCI_ExecuteStmt(st, MT("create type test_t as object ")
                    MT("( ")
                    MT("    val_int  number, ")
                    MT("    val_flt  float, ")
                    MT("    val_dbl  float, ")
                    MT("    val_str  varchar2(30), ")
                    MT("    val_date date, ")
                    MT("    val_lob  clob, ")
                    MT("    val_file bfile, ")
                    MT("    val_obj  type_t, ")
                    MT("    val_raw  raw(10) ")
                    MT(")"));

    OCI_ExecuteStmt(st, MT("create type t_tab1_emp as VARRAY(100) of varchar2(50)"));

    OCI_ExecuteStmt(st, MT("create type t_tab2_emp as table of varchar2(50)"));

    /* create table for the demo */
    OCI_ExecuteStmt(st, MT("create table test_fetch(code int, article ")
                        MT("varchar2(30), price float, creation date)"));

    OCI_ExecuteStmt(st, MT("create table test_long_raw(code int, content long raw)"));

    OCI_ExecuteStmt(st, MT("create table test_long_str(code int, content long)"));

    OCI_ExecuteStmt(st, MT("create table test_lob(code int, content clob)"));

    OCI_ExecuteStmt(st, MT("create table test_object(val test_t)"));

    OCI_ExecuteStmt(st, MT("create table test_table_obj of type_t"));

    OCI_ExecuteStmt(st, MT("create table test_array ")
                        MT("( ")
                        MT("    val_int  number, ")
                        MT("    val_dbl  float, ")
                        MT("    val_flt  float, ")
                        MT("    val_str  varchar2(30), ")
                        MT("    val_date date, ")
                        MT("    val_lob  clob, ")
                        MT("    val_file bfile ")
                        MT(")")
                    );

    OCI_ExecuteStmt(st, MT("create table test_coll_varray ")
                        MT("( ")
                        MT("    departement number, ")
                        MT("    employees   t_tab1_emp ")
                        MT(")")
                    );

    OCI_ExecuteStmt(st, MT("create table test_coll_nested ")
                        MT("( ")
                        MT("    departement number, ")
                        MT("    employees   t_tab2_emp ")
                        MT(") nested table employees store as test_table_emp")
                    );

    OCI_ExecuteStmt(st, MT("create table test_directpath(val_int number(8,4), ")
                        MT(" val_str varchar2(30), val_date date)"));

    /* insert data into the demo tables */
    OCI_ExecuteStmt(st, MT("insert into test_fetch ")
                        MT("(code, article, price, creation) ")
                        MT("values (1, 'shoes', 3.14, to_date('1978-12-23', 'YYYY-MM-DD'))"));

    OCI_ExecuteStmt(st, MT("insert into test_fetch ")
                        MT("(code, article, price, creation) ")
                        MT("values (2, 'shirt', 5.99, to_date('1999-09-12', 'YYYY-MM-DD'))"));

    OCI_ExecuteStmt(st, MT("insert into test_lob(code,content)  ")
                        MT("values (1, EMPTY_CLOB())"));

    OCI_ExecuteStmt(st, MT("insert into test_long_str(code,content) ")
                        MT("values (1, 'Rugby rocks !')"));

    OCI_ExecuteStmt(st, MT("insert into test_coll_varray(departement,employees) ")
                        MT("values (1, t_tab1_emp('Peter', 'John', 'Paula', 'Gina'))"));

    OCI_ExecuteStmt(st, MT("insert into test_coll_varray(departement,employees) ")
                        MT("values (2, t_tab1_emp('Ben', 'Alice', 'Joel', 'Maria'))"));

    OCI_ExecuteStmt(st, MT("insert into test_coll_nested(departement,employees) ")
                        MT("values (1, t_tab2_emp('Vince', 'Richard', 'Rita', 'Sophia'))"));

    OCI_ExecuteStmt(st, MT("insert into test_coll_nested(departement,employees) ")
                        MT("values (2, t_tab2_emp('Paul', 'Sarah', 'Robert', 'Zoe'))"));

    OCI_ExecuteStmt(st, MT("insert into test_table_obj values(type_t(1, 'shoes'))"));
    OCI_ExecuteStmt(st, MT("insert into test_table_obj values(type_t(2, 'pen'))"));

    OCI_Commit(cn);
}

//删除表
void drop_tables(void)
{
    print_text("\n>>>>> DROPPING TABLES AND TYPES \n\n");

    OCI_ExecuteStmt(st, MT("drop table test_fetch"));
    OCI_ExecuteStmt(st, MT("drop table test_long_str"));
    OCI_ExecuteStmt(st, MT("drop table test_long_raw"));
    OCI_ExecuteStmt(st, MT("drop table test_lob"));
    OCI_ExecuteStmt(st, MT("drop table test_array"));
    OCI_ExecuteStmt(st, MT("drop table test_object"));
    OCI_ExecuteStmt(st, MT("drop table test_coll_varray"));
    OCI_ExecuteStmt(st, MT("drop table test_coll_nested"));
    OCI_ExecuteStmt(st, MT("drop table test_table_obj"));
    OCI_ExecuteStmt(st, MT("drop table test_directpath"));

    OCI_ExecuteStmt(st, MT("drop type  test_t"));
    OCI_ExecuteStmt(st, MT("drop type  type_t"));
    OCI_ExecuteStmt(st, MT("drop type  t_tab1_emp"));
    OCI_ExecuteStmt(st, MT("drop type  t_tab2_emp"));

}

//测试格式语句
void test_format(void)
{
    int code = 1;

    print_text("\n>>>>> TEST FORMATTING \n\n");

    OCI_ExecuteStmtFmt(st, MT("select * from test_fetch where code = %i"), code);

    rs = OCI_GetResultset(st);

    while (OCI_FetchNext(rs))
    {
        print_frmt("> code : %i", OCI_GetInt(rs, 1));
        print_text(", action : "); print_dstr(OCI_GetString(rs, 2));
        print_frmt(", price : %g", OCI_GetDouble(rs,3));
        print_text(", date : "); print_dstr(OCI_GetString(rs, 4));
        print_text("\n");
   }

    print_frmt("\n%d row(s) fetched\n", OCI_GetRowCount(rs));
}

//测试直接语句
void test_immediate(void)
{
    int code = 1;

    print_text("\n>>>>> TEST IMMEDIATE \n\n");

    OCI_Immediate(cn, MT("select code, article from test_fetch where code = 1"),
                  OCI_ARG_INT, &code,
                  OCI_ARG_TEXT, temp);

    print_frmt("> code : %i ", code);
    print_text("- article : "); print_dstr(temp);
    print_text("\n");
}

//测试取语句
void test_fetch(void)
{
    int i, n;

    print_text("\n>>>>> SIMPLE TEST FETCH WITH META DATA\n\n");

    /* execute query in one go */
    OCI_ExecuteStmt(st, MT("select * from test_fetch"));

    rs = OCI_GetResultset(st);
    n  = OCI_GetColumnCount(rs);

    /* print resultset columns info */
    for(i = 1; i <= n; i++)
    {
        OCI_Column *col = OCI_GetColumn(rs, i);

        print_frmt("> Field : #%i ", i);
        print_text("- Name  : "); print_mstr(OCI_ColumnGetName(col));
        print_text("\n");
    }

    print_text("\n");

    /* print resultset content */
    while (OCI_FetchNext(rs))
    {
        print_frmt("> code : %i", OCI_GetInt(rs, 1));
        print_text(", action : "); print_dstr(OCI_GetString(rs, 2));
        print_frmt(", price : %g", OCI_GetDouble(rs,3));
        print_text(", date : "); print_dstr(OCI_GetString(rs, 4));
        print_text("\n");
    }

    print_frmt("\n%d row(s) fetched\n", OCI_GetRowCount(rs));
}

//测试绑定语句
void test_bind1(void)
{
    int code = 1;

    print_text("\n>>>>> TEST BINDING \n\n");

    /* execute query in three steps */
    OCI_Prepare(st, MT("select * from test_fetch where code = :code"));
    OCI_BindInt(st, MT(":code"), &code);
    OCI_Execute(st);

    rs = OCI_GetResultset(st);

    /* print resultset content */
    while (OCI_FetchNext(rs))
    {
        print_frmt("> code : %i", OCI_GetInt(rs, 1));
        print_text(", action : "); print_dstr(OCI_GetString(rs, 2));
        print_frmt(", price : %g", OCI_GetDouble(rs,3));
        print_text(", date : "); print_dstr(OCI_GetString(rs, 4));
        print_text("\n");
    }

    print_frmt("\n%d row(s) fetched\n", OCI_GetRowCount(rs));
}

//测试分段插入语句
void test_piecewise_insert(void)
{
    FILE *f;

    print_text("\n>>>>> TEST PIECEWISE INSERTING\n\n");

    /* this code could have been used with a text file in a LONG column
       as well...  */

    /* open the app file in for reading*/

    f = fopen(EXE_NAME, "rb");

    if (f)
    {
        int n;
        OCI_Long *lg;
        unsigned char buffer[SIZE_BUF];

        fseek (f , 0 , SEEK_END);
        n = ftell(f);
        rewind (f);

        print_frmt("\n%d bytes to write\n", n);

        lg = OCI_LongCreate(st, OCI_BLONG);

        /* execute query in three steps */
        OCI_Prepare(st,  MT("insert into test_long_raw(code, content) ")
                         MT("values (1, :data)"));

        OCI_BindLong(st, MT(":data"), lg, n);
        OCI_Execute(st);

        /* write data into table by chunks of 2048 bytes */
        while ((n = (int) fread(buffer, 1, sizeof(buffer), f)))
        {
            OCI_LongWrite(lg, buffer, n);
        }

        print_frmt("\n%d bytes written\n", OCI_LongGetSize(lg));
        fclose(f);

        OCI_LongFree(lg);
        OCI_Commit(cn);
    }
}

……

感兴趣的同学详细看项目源码包了!~

学习的目标是成熟!~~~~~~~~~

源码包下载(附开发说明文档)!


你可能感兴趣的:(开源项目之Oracle驱动 OCILIB)