我想通過我的C#代碼來處理UPDATE語句。我用下面...SqlCommand.ExecuteNonQuery()總是返回0
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
cmd.Parameters.AddWithValue("@CUSTOMER", intCustomer);
cmd.Parameters.AddWithValue("@CONDITION", strCondition);
cmd.Parameters.AddWithValue("@BOOK", strBook);
cmd.Parameters.AddWithValue("@PAGE", strPage);
cmd.Parameters.AddWithValue("@ENDPAGE", strEndPage);
System.Diagnostics.Debug.WriteLine("Expanded query: " +
query.ExpandSqlQuery(cmd.Parameters));
int affectedRows = cmd.ExecuteNonQuery();
System.Diagnostics.Debug.WriteLine("Number of rows affected: " + affectedRows);
}
我曾嘗試與不只是調試PARAMS要做到這一點,總是出於某種原因獲得0
返回值。
我已經提出,擴大PARAMS給我看實際的查詢(不變量)小的擴展方法...
public static string ExpandSqlQuery(this String input, SqlParameterCollection sqlParams)
{
string results = input;
foreach (SqlParameter p in sqlParams)
results = results.Replace(p.ParameterName, p.Value.ToString());
return results;
}
...我叫權執行查詢之前,看看有什麼會被跑。
System.Diagnostics.Debug.WriteLine("Expanded query: " +
query.ExpandSqlQuery(cmd.Parameters));
然後我去,在C#返回0受影響的行是完全相同的查詢和手動運行它Microsoft SQL Server Management Studio
有它告訴我1
行受到影響!
使用參數查詢是...
UPDATE
BookList
SET
Overdue=2
WHERE
[email protected]
and Condition='@CONDITION'
and Book='@BOOK'
and Page='@PAGE'
and EndPage='@ENDPAGE'
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
[email protected]
and Condition='@CONDITION'
and Book='@BOOK';
擴展查詢是...
UPDATE
BookList
SET
Overdue=2
WHERE
Customer=85
and Condition='old'
and Book='00103'
and Page='00304'
and EndPage='00304'
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
Customer=85
and Condition='old'
and Book='00103';
任何想法如何,我可以去調試這個問題?
你可以發表你的更新查詢 – Niladri
仔細檢查您的連接字符串,請確保您連接到相同的SQL數據庫?我只是建議這樣做,因爲我之前已經完成了... –
您是否能夠對服務器運行SQL Server Profiler,以驗證您從C#代碼看到的查詢與服務器上正在執行的查詢是否相同? –