2013-06-18 24 views
1

下探領先的數字我想用一個where子句,它看起來像SqlDataAdapter的,SqlCommand的從字符串

string s2 = "Select * from idtyfile where oysterid=" + id ; 
SqlCommand da2 = new SqlCommand(s2, con); or 
SqlAdapter da2 = new SqlAdapter(s2, con); 

這兩個當我試圖執行這些

da2.ExecuteReader(); 
都未能執行SQL語句

在ID數據的模樣

ID 
43PCOU5T 
ZP6RAEJ0 

出於某種原因,這兩個查詢的是輝關於這些數據。

+0

爲什麼不格式化查詢字符串並將ID作爲參數傳遞給..? – MethodMan

回答

8

您在選擇命令中缺少單引號,這是導致原始SELECT失敗的原因。不過,我想指出的是,您應該始終將您的SqlCommand/SqlConnection參數化並封裝在using聲明中。以下將是一個更清潔更安全的方式來解決您的問題。

 string s2 = "Select * from idtyfile where [email protected]"; 
     DataTable myDataTable = new DataTable(); 

     using (SqlConnection conn = new SqlConnection(myConnectionString)) 
     using (SqlCommand cmd = new SqlCommand(s2, conn)) 
     { 
      cmd.Parameters.AddWithValue("@id", id); 
      conn.Open(); 
      myDataTable.Load(cmd.ExecuteReader()); 
     } 

對於某些教育資源,您應該查看以下鏈接。

MSDN Reference for the using keyword

MSDN Reference for SqlCommand - 看看Parameters財產。

+1

dataReader也是一次性對象,應該用using語句包裝。 – BenR

+0

我沒有實例化讀者對象。在'SqlCommand'上調用'ExecuteReader'擴展方法,它將被'SqlCommand'處置。希望OP知道如何處理來自'cmd.ExecuteReader()'的數據。 –

+0

其實我想將我從Select語句獲得的值存儲到DataTable中。我可以使用SQL Adapter而不是SQL Command嗎? – Huzaifa