Oracle通过OCI批量加载需要注意的问题
采用OCI的最大好處就是:它是最切近Oracle底層的技術,因此,效率是最高的。同時,它是跨平臺的。因此,在我給出的ORADBI庫,除了OCI之外,沒有其他外部依賴,稍加改動,就可以移植到非Windows平臺上或其他嵌入式平臺。
然而,OCI也比較不容易使用。它的功能之強,粒度之細,語法之煩瑣,都不適合今天熟悉了快速開發模式的人員使用。然而,OCI的高效,直接根植于數據庫核心,跨平臺的語言特性,是其他如OO4O、OLEDB、ADO等COM方式不具備的。
下面就從之前一段時間參與SN數據庫集群中間件開發的實踐中積累的一點經驗,分享如下:
1.支持的類型 char , unsigned char, int, double,float,long ,char*
大部分類型直接調用接口不會出什么問題,但是char*尤其需要注意,容易出現亂碼。
2.加載的流程大致如下:
建立連接-》準備sql statement -》 綁定數據-》excute-》commit
對于字符串數據的加載的,需要采用三維數組,表中字符串類型的列數為一維,行數為第二維,每個字段的長度為第三維。
三維數組的變量聲明必須與excute的調用在同一個作用域內,否則,execute的時候,三維數組的所在的內存可能已經被重新分配,execute讀取綁定數據便會出現亂碼。
此處比較容易出錯,雖然execute并沒有顯示的調用綁定的數據變量,但是內部實現確實讀取綁定變量的數據批量加載到數據庫中。此處不注意,容易導致加載數據變成亂碼。并且此錯誤是偶發性錯誤,不是每次運行都會出現,畢竟內存分配是隨機的。
3.加載NULL字段。
批量加載的接口都是逐列加載某種類型的數據,并且保證各列之間通過位置保證一行數據的對應關系,那么如果一列數據中有NULL字段又該如何呢?
OCI接口中也是支持NULL數據加載的,是通過indicator(指示器)實現的。indicator是一個指針,類型是sb2,可以指向一個字段,也可以指向一列字段。在綁定接口:OCIBindByPos(stmthp,&bindhp,errhp,1,?(dvoid?*)&aa,4,?SQLT_INT,?(void*)&indicator,?NULL,?NULL,0,0,0); 作為參數傳入,其元素數目與綁定的數據列表aa的元素數目相等。位置一一對應。indicator對應位置為-1
的表示寫入NULL,>=0表示寫入數據列表aa中的值。
下面是官方文檔中,對指示器使用的介紹。
1.加載,數據寫入NULL:
Input
For input host variables, the OCI application can assign the following values to an indicator variable:
Table 2-7 Input Indicator Values
| -1 | Oracle assigns a NULL to the column, ignoring the value of the input variable. |
| >=0 | Oracle assigns the value of the input variable to the column. |
?2.查詢,數據讀取NULL:
Output
On output, Oracle can assign the following values to an indicator variable:
Table 2-8 Output Indicator Values
| -2 | The length of the item is greater than the length of the output variable; the item has been truncated. Additionally, the original length is longer than the maximum data length that can be returned in the sb2 indicator variable. |
| -1 | The selected value is null, and the value of the output variable is unchanged. |
| ? 0 | Oracle assigned an intact value to the host variable. |
| >0 | The length of the item is greater than the length of the output variable; the item has been truncated. The positive value returned in the indicator variable is the actual length before truncation. |
Indicator Variables for Named Data Types and REFs
?
?
?
?
?
?
?
?
參考文獻:
1.OCI安裝部署以及常用的OCI函數介紹
http://www.cnblogs.com/joeblackzqq/archive/2011/04/24/2026461.html
2. OCI讀取單條記錄
http://www.cnblogs.com/joeblackzqq/archive/2011/04/26/2028847.html
3.OCI寫入NULL
http://blog.csdn.net/spche/article/details/6195322
轉載于:https://www.cnblogs.com/qianxun/archive/2013/06/03/3115645.html
總結
以上是生活随笔為你收集整理的Oracle通过OCI批量加载需要注意的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle命令--数据文件被误删后的处
- 下一篇: 用libevent实现简易的telnet