odp.net使用時,指定的轉換無效

正在作數據庫備份與還原。數據庫

我用odp.net經過存儲過程+OracleDataAdapter,將數據表直接返回到dataset中,但提示「指定的轉換無效」。我就納悶了,爲何報表應用及查詢時,不報這個錯,而導出物理表,就報這個錯呢。c#

查資料得知緣由: app

the OracleDataAdapter class attempts to map Oracle native data types to .NET data typeside

NUMBER,  DATE , TIMESTAMP , TIMESTAMP WITH LOCAL TIME ZONE  ,TIMESTAMP WITH TIME ZONE , INTERVAL DAY TO SECOND this

上面幾種類型可能因爲數據庫精度和.net的精度 不一樣,引發異常。好比數據庫number是38位,但Decemal只是28位。spa

 Oracle decided that the best way to store these types of data in a Dataset object without losing any detail would be either as a byte array or a string.net

oracel建議用戶 manually define this mapping!
code

_myAdapter.SafeMapping.Add("LaunchDate", typeof(string));                              _myAdapter.SafeMapping.Add("ExpiryDate", typeof(byte[])); orm

那這麼多表,我怎麼知道哪一個列的精度不對呢?我全部的數據都是number類型。因而寫了段代碼,ci

用OracleDataReader循環讀列,找出問題列!        

OracleDataReader reader = cmd.ExecuteReader();
int x = 0;
do
{
    Trace.WriteLine("表" + (++x));
    while (reader.Read())
    {
        string result = reader.GetString(3) + "-" + reader.GetString(4) + "+";
        for (int j = 6; j < reader.FieldCount - 1; j++)
        {
            try
            {
                if (!reader.IsDBNull(j) && reader.GetFieldType(j)==typeof( decimal))  
                    result += (reader.GetDecimal(j).ToString() + ",");
                else
                    result += ("null,");
            }
            catch (Exception ex)
            {
                Trace.WriteLine("wrong filed "+j+"   "+result);
                conn.Close();
                throw;
            }
        }
        Trace.WriteLine(result);
    }
} while (reader.NextResult());

終於找到了 問題列!

其實用到幾處OracleDataReader 的知識點

reader.Read()  reader.IsDBNull(j)  reader.GetFieldType(j)  reader.NextResult()

NextResult就是在多個結果集間循環。由於我過程一次性返回了20個遊標集。

你們看,用OracleDataReader就是如此複雜,但我已經找到了問題列,從庫裏把數據修改爲精度之內以後。就能夠這樣:

OracleDataAdapter oda = new OracleDataAdapter(cmd);

oda.Fill(ds);

就兩句話,一次性把全部的表通通轉存到了dataset中去。不要太爽好很差

相關文章
相關標籤/搜索