2014-01-28 35 views
1
protected void Button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection("Data Source=HKGROX-PC\\SQLEXPRESS;Initial Catalog=example;Integrated Security=True"); 
     con.Open(); 
     string value = DropDownList1.SelectedValue.ToString(); 

     switch (value) 
     { 
      case "BJP": 
       string s = "select BJP from noofvotes where year= "+ DropDownList2.Text+" and const=" + DropDownList3.SelectedValue + ""; 
       SqlCommand cmd = new SqlCommand(s,con); 
       DataSet ds = new DataSet(); 
       SqlDataAdapter sda = new SqlDataAdapter(cmd); 
       sda.Fill(ds); 
       if (ds.Tables[0].Rows.Count > 0) 
       { 
        DataRow dr = ds.Tables[0].Rows[0]; 
        TextBox1.Text = dr["BJP"].ToString(); 
       } 
       break; 

     } 
     con.Close(); 
    } 

這裏我得到了無效的列名'Rohini'。我有一個表格,將這些值傳遞給列表框。請檢查我的查詢中的錯誤,我收到「無效的列名稱」錯誤。

+1

年是一個保留關鍵字。什麼是你的表的真實列名? – Steve

+1

你在哪裏看到這個錯誤?這段代碼中沒有提到'Rohini'? – christiandev

+1

我想'DropDownList3.SelectedValue'包含值「Rohini」,它不被'''包圍,所以它被解釋爲一列('where const = Rohini')。按照@Steve的建議使用參數。 – CodeCaster

回答

-1

如果您的列(年份爲& const)爲Varchar2類型,則使用單引號。

string s = "select BJP from noofvotes where year= '"+ DropDownList2.Text+"' and const='" + DropDownList3.SelectedValue + "'"; 
SqlCommand cmd = new SqlCommand(s,con); 

如果列(年&常數),你必須使用像下面列數:

string s = "select BJP from noofvotes where year= "+ Convert.ToInt32(DropDownList2.Text)+" and const=" + Convert.ToInt32(DropDownList3.SelectedValue) + ""; 
SqlCommand cmd = new SqlCommand(s,con); 
3

假設你真的有一個名爲YEAR和const我想補充,以避免混淆錯誤

string s = "select BJP from noofvotes where [year]= @yval and [const][email protected]"; 
SqlCommand cmd = new SqlCommand(s,con); 
cmd.Parameters.AddWithValue("@yval",DropDownList2.Text); 
cmd.Parameters.AddWithValue("@cval",DropDownList3.SelectedValue); 
.... 
列清單

將方括號中的保留字YEAR括起來將允許您將該名稱作爲列標識符(雖然這實際上是一種不好的做法)。 CONST字不保留,但由於衆所周知的語言關鍵字,我也感到困惑。

上面的查詢中的另一個問題(肯定是第一個錯誤的來源)是DrowpDownList3的SelectedValue屬性。它被插入到查詢中,而不用單引號括起來。如果我想象它包含單詞Rohini那麼你的原始文本變得像這樣

string s = "select BJP from noofvotes where year=2014 and const=Rohini"; 

,並以這種方式,該值被認爲是像列名

再次,把它作爲一個參數該查詢應該可以解決問題。

+1

'const'不是關鍵字。但是你也可以在方括號中使用它。 –

+0

好吧,但我覺得很困惑:-) – Steve

+0

@ user1517636你能解釋一下這裏的編輯嗎? – Steve

0

如果你想速戰速決替換此:

string s = "select BJP from noofvotes where year= "+ DropDownList2.Text+" and const=" + DropDownList3.SelectedValue + ""; 

有了這個:

​​

如果你想要一個更安全的修復程序,使用SqlParameter小號只要有可能,它會不斷黑客遠離你數據庫。

string s = "SELECT BJP FROM noofvotes WHERE [year]= @year AND [email protected]"; 
SqlCommand cmd = new SqlCommand(s, con); 
cmd.Parameters.AddWithValue("@year", DropDownList2.Text); 
cmd.Parameters.AddWithValue("@const", DropDownList3.SelectedValue);