今天寫代碼時,遇到一個問題,解決之后,然后想記錄一下,於是就申請開通博客,本人是菜鳥,問題可能比較簡單
using (SqlConnection con = getConnect()) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (con.State == ConnectionState.Closed) { con.Open(); } result = (int)cmd.ExecuteScalar(); } }
using (SqlConnection con = getConnect()) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (con.State == ConnectionState.Closed) { con.Open(); } result = cmd.ExecuteNonQuery(); } }
就是在查詢一個 select count(id) from UrgentOrder where orgid='' ,獲取集合數的時候,第一次使用了
ExecuteNonQuery ,然后怎么查返回都是-1(result初始值-1),我還以為sql寫的問題,放入數據庫中查詢是正確的,然后我就納悶了,,去翻一下資料了,
發現這個是返回受影響的數值,增加,更新,刪除的情況。
ExecuteScalar 而這個是執行查詢,並返回查詢所返回的結果集中第一行的第一列。忽略其他列或行。
20191109記