2012-10-11 45 views
0
protected void DropDownServerName_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_Shared_NotebookConnectionString"].ConnectionString); 

     conn.Open(); 

     string serverName = DropDownServerName.SelectedValue; 

     string sqlquery = ("SELECT Architecture FROM tblServer WHERE (ServerName = " + serverName + ")"); 

     SqlCommand command = new SqlCommand(sqlquery, conn); 

     txtUpdateArchitecture.Text = command.ExecuteScalar().ToString(); 

     conn.Close(); 
    } 

DropDownServerName已連接到SQL Server使用SqlDataSource顯示ServerName列上的值列表。從sql server獲取數據到文本框錯誤消息

當我得到一個名爲「Brad」的選擇值,並且我希望來自Brad的Architecture列的值顯示在文本框中。但是,我得到錯誤說,無效的列名稱「布拉德」。該列假設爲ServerName,而Brad只是ServerName列中的一個值。

回答

0

試試這個。它應該與單引號一起工作。

string sqlquery = ("SELECT Architecture FROM tblServer WHERE ServerName = '" + serverName + "'"); 
+2

從來沒有像這樣連接,使用參數 –

3

您需要報價在你的服務器名

string sqlquery = ("SELECT Architecture FROM tblServer WHERE (ServerName = '" + serverName + "')"); 

或者更好的是,使用參數化查詢[它是更安全的,針對SQL注入和有趣的字符的字符串,污染你的查詢]

string sqlquery = "SELECT Architecture FROM tblServer WHERE ServerName = @ServerName"; 

SqlCommand command = new SqlCommand(sqlquery, conn); 
command.Parameters.AddWithValue("@ServerName", serverName); 
+4

更好的是,使用參數來避免SQL注入。 – Patko

+0

很好,其他人告訴這個人連接,而不是告訴他使用參數 –

+0

也許SO應該有一些算法來檢測這個,並將重定向到http://stackoverflow.com/questions/601300/what-is-sql-injection或類似的東西:) – Patko

0

在WHERE子句中在servername周圍添加'':

... WHERE ServerName = '" + serverName + "' ... 
+1

從來沒有像這樣連接,使用參數 –

0

您可能缺少變量周圍的單引號。試試這個

protected void DropDownServerName_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_Shared_NotebookConnectionString"].ConnectionString); 

     conn.Open(); 

     string serverName = DropDownServerName.SelectedValue; 

     string sqlquery = ("SELECT Architecture FROM tblServer WHERE (ServerName = '" + serverName + "')"); 

     SqlCommand command = new SqlCommand(sqlquery, conn); 

     txtUpdateArchitecture.Text = command.ExecuteScalar().ToString(); 

     conn.Close(); 
    } 
+0

您已經引入了更多的語法錯誤到該查詢中**引號錯誤放置**。但我沒有downvote – codingbiz

+0

@codingbiz謝謝我已經糾正它,雖然我的答案是不正確的。其他人發佈了有關使用參數化查詢而不是在同一個查詢中使用單引號的正確答案。 – jags

+0

您的回答是正確的,但出於安全原因不鼓勵。 – codingbiz