2015-10-26 40 views
-1

我試圖插入一個有小數點位置的記錄,例如:7654.00,此列的數據類型爲numeric(10,12)但我得到算術溢出錯誤,我知道我需要先做一個轉換,但不知道如何......在asp.net中將varchar轉換爲數據類型數值的算術溢出錯誤

我遇到問題的列是TotalCost

以下是我有:

string FullName = row.Cells[1].Text; 
string TotalCost = row.Cells[6].ToString(); 

using (SqlConnection myCon = new SqlConnection(myConnStr)) 
{ 
    using (SqlCommand myCmd = new SqlCommand()) 
    { 
     myCmd.Connection = myCon; 
     myCmd.CommandType = CommandType.Text; 
     myCmd.CommandText = @"insert into myTable (FullName, TotalCost) 
           values(@FullName, @TotalCost)"; 
     myCmd.Parameters.AddWithValue("@FullName", FullName.ToString()); 

     myCmd.Parameters.AddWithValue("@TotalCost", TotalCost) 

     myCon.Open(); 
     myCmd.ExecuteNonQuery(); 
     myCon.Close(); 
    } 
} 
+0

如果'TotalCost'是數字,那麼就需要將其轉換爲十進制\雙,然後作爲'myCmd.Parameters.AddWithValue通過(「@ TotalCosts」) ' –

+0

AddWithValue無法知道你傳遞了一個double如果第二個參數是一個字符串。避免它 – Steve

+1

'NUMERIC(10,12)'是不可能的 - 這將意味着一個數字與** 10位**所有在一起,** 12其中**在小數點右側.... –

回答

1

AddWithValue是一個方便的快捷方式添加參數,但在這兩個博客文章解釋存在嚴重的侷限性

Can We Stop using AddWithValue already?
How Data Access Code Affects Database Performance

在你的情況下,你傳遞一個字符串作爲參數AddWithValue中的第二個參數@TotalCostAddWithValue,認真地將字符串傳遞給您的數據庫引擎,導致提到的錯誤。

您應該將字符串轉換爲十進制值(它似乎更適合使用貨幣值的十進制),然後使用您的數據類型的更露骨聲明中加入參數

string TotalCost = row.Cells[6].ToString(); 
decimal cost; 
if(!decimal.TryParse(TotalCost, out cost)) 
    // Put here an error message for your user 
    // "The value cannot be converted to a decimal value" 
else 
{ 
    using (SqlConnection myCon = new SqlConnection(myConnStr)) 
    using (SqlCommand myCmd = new SqlCommand()) 
    { 
     myCmd.Connection = myCon; 
     myCmd.CommandType = CommandType.Text; 
     myCmd.CommandText = @"insert into myTable (FullName, TotalCost) 
           values(@FullName, @TotalCost)"; 
     myCmd.Parameters.Add("@FullName", SqlDbType.NVarChar).Value = FullName; 
     myCmd.Parameters.Add("@TotalCost", SqlDbType.Decimal).Value = cost; 
     myCon.Open(); 
     myCmd.ExecuteNonQuery(); 
    } 
} 

當然,你應該適應這個代碼到你TotalCost列的實際數據類型的數據表

相關問題