2016-08-21 72 views
0

我收到此錯誤轉換爲varchar值「Thowheed」 int數據類型時如何解決這個轉換錯誤失敗?

轉換失敗。

筆者走訪和堆棧溢出檢查,但我無法找到答案

我的附加價值在下拉列表中,一旦我選擇,然後點擊確定按鈕,它給我從數據庫中的記錄。

這是我的代碼

string cs = ConfigurationManager.ConnectionStrings["Nibrass_DBConnectionString"].ConnectionString; 

using (SqlConnection con = new SqlConnection(cs)) 
{ 
    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = con; 

    cmd.CommandText = "SELECT Date as Date,Credit, Debit_From as Received_From, Credit_Amount as amount, Reason From Transaction_Credit where Credit = " + DropDownListSelectAccount.SelectedValue+ " or cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + " ORDER BY Date DESC"; 

    con.Open(); 
    SqlDataReader rd = cmd.ExecuteReader(); 

    while(rd.Read()) 
    { 
     DateTime dt = Convert.ToDateTime(rd[0]); 
     string receivedFrom = rd[1].ToString(); 
     int amount = Convert.ToInt32(rd[2]); 
    } 

    con.Close(); 
} 

我的數據庫表的定義是

CREATE TABLE [dbo].[Transaction_Credit] 
(
    [Date]   DATE   NOT NULL, 
    [Credit]  VARCHAR (50) NOT NULL, 
    [Debit_From] VARCHAR (50) NOT NULL, 
    [Reason]  VARCHAR (100) NULL, 
    [Credit_Amount] INT   NOT NULL, 
    [Balance]  INT   NULL 
); 
+1

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您應該**不**將您的SQL語句連接在一起 - 使用**參數化查詢**來代替,以避免SQL注入 –

回答

1

這是您的查詢:

select Date as Date, Credit, Debit_From as Received_From, 
     Credit_Amount as amount, Reason 
from Transaction_Credit 
where Credit = " + DropDownListSelectAccount.SelectedValue+ " or 
     cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + " 
order by Date DESC; 

的讀碼是這樣的:

int amount = Convert.ToInt32(rd[2]); 

但第三列是Received_From,而不是amount。這可能是你的問題。

另外,cast(Debit_From as varchar)危險。如果不包含varchar()的長度,SQL Server將根據上下文插入一個長度。只要不需要轉換就不需要轉換。

2

您不應串聯您的字符串。這是一種不好的做法,您的代碼易受SQL Injection的影響。

你應該用參數來代替:

cmd.CommandText = @" 
    SELECT Date 
     , Credit 
     , Debit_From AS Received_From 
     , Credit_Amount AS Amount 
     , Reason 
    FROM Transaction_Credit 
    WHERE Credit = @DropDownListSelectAccount 
     OR Debit_From = @DropDownListSelectAccount 
    ORDER BY Date DESC"; 

cmd.Parameters.Add("@DropDownListSelectAccount", SqlDbType.VarChar, 50). Value) = DropDownListSelectAccount.SelectedValue; 

順便說一句,你不需要投Debit_From爲VARCHAR,因爲它已經像在你的數據庫。

+0

你應該檢查[我們可以停止使用AddWithValue()了嗎?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/ can-we-stop-using-addwithvalue-already /)並停止使用'.AddWithValue()' - 它可能會導致意外的和令人驚訝的結果... –

+0

@marc_s永遠不會知道它。我是一個數據庫開發人員,而不是c#。我試圖指出OP不應該串聯字符串來構建他的查詢。但我會更新我的答案。我學到的東西。謝謝! –

相關問題