我在.NET 2.0中使用C#,並試圖訪問和操作數據庫。我可以從數據庫,因爲我想讀多次和一切正常,但只要我嘗試插入一個項目,我得到了以下錯誤消息:C#SQL查詢異常
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
我想看看這件事,但我找到的修復程序無效或不適用。
我有以下代碼:
using (SqlConnection conn = new SqlConnection(SQLConnectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT [Col1] FROM [Table1] WHERE [Col2]='" + val2 + "'", conn);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables.Count == 0 || dataSet.Tables[0].Rows.Count != 1)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
cmd.ExecuteNonQuery();
}
}
注:我敢肯定,我的權限設置不當,因爲Visual Studio可以用相同的SQLConnectionString插入。另外,我對數據庫還是一個相當新的東西,所以如果我做了任何錯誤的事情,請告訴我。
謝謝。
出於某種原因,我認爲「使用」命令處理打開和關閉,而不是隻是關閉。這工作,謝謝。 – user108088 2010-07-19 08:25:20