對於那些正在使用SQL命令並且出現錯誤「無法添加數據連接的錯誤,ExecuteScalar需要一個開放的可用連接,連接的當前狀態已關閉。試試這個:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
// query to select all the rows whose column name is the same as id
comm.CommandText = "SELECT COUNT(*) from tableName where colName like @val1";
comm.Connection = conn;
conn.Open(); // <---- adding this line fixed the error for me
comm.Parameters.AddWithValue("@val1", id);
// retrieve how many rows are returned after executing the query
count = (int)comm.ExecuteScalar(); // < --- where the error originally occurred
}
}
重新啓動您的計算機。 – 2010-09-13 19:02:46
那有效......背後的故事是什麼? – Steven 2010-09-13 19:13:07
我不知道,只是一個建議。 – 2010-09-13 21:23:38