2013-11-24 103 views
0

我試圖使用這個Update命令,但它不能正常工作。當我在SQL Server 2008中運行它,但不能在Visual Studio 2012Visual Studio 2012更新查詢

SqlCommand cmd= new SqlCommand("UPDATE dwh_staging_table SET pestpopulation1 = @avg_pest1 WHERE DistrictName = @DistrictName and TownName = @TownName And VarietyOfCrop = @V_Crop And pestpopulation1 = @pest", con1); 
cmd.Parameters.AddWithValue("@avg_pest1",16); 
cmd.Parameters.AddWithValue("@DistrictName", "Multan"); 
cmd.Parameters.AddWithValue("@TownName","Ambala"); 
cmd.Parameters.AddWithValue("@V_Crop","NIAB 999"); 
cmd.Parameters.AddWithValue("@pest",0); 

adapter.UpdateCommand = cmd; 
+0

其中petpopulation爲零它不產生任何錯誤其只是不updatng值當我運行在MS SQL Server 2008相同的查詢它的工作原理.. – user1056466

+0

您正在分配更新命令來選擇適配器命令檢查我的答案,並使用參數terrie查詢,以避免SQL注入攻擊 –

回答

3

您分配Sql Update CommandSqlDataAdapterSelectCommand這是工作。

試試這個:

adapter.UpdateCommand = new SqlCommand("your update command"); 

注:您的更新命令是開放的SQL injection attacks
使用PARAMETERISED QUERIES來避免它們。

參數化查詢示例:

SqlCommand cmd=new SqlCommand("update products set [email protected] where [email protected]"); 

cmd.Parameters.AddWithValue("@price",1234); 
cmd.Parameters.AddWithValue("@id",12); 

adapter.UpdateCommand=cmd; 

完整的解決方案:(使用參數化查詢)

SqlCommand cmd = new SqlCommand("UPDATE dwh_staging_table SET [email protected] WHERE [email protected] and [email protected] And [email protected] And [email protected]", con1); 

cmd.Parameters.AddWithValue("@pestpopulation1", row[3]); 
cmd.Parameters.AddWithValue("@DistrictName", row[0].ToString()); 
cmd.Parameters.AddWithValue("@TownName", row[1].ToString()); 
cmd.Parameters.AddWithValue("@VarietyOfCrop", row[2].ToString()); 
cmd.Parameters.AddWithValue("@pestpopulation11", 0); 

adapter.UpdateCommand = cmd; 
+0

仍然無法更新.. – user1056466

+0

@ user1056466:檢查我的編輯答案與節'完整的解決方案' –

+0

@ user1056466:調用.ToString()上的區名,城鎮,VarietyOfCrop命令參數我的答案,檢查我編輯的版本。 –