1. 程式人生 > >C#.net mysql There is already an open datareader associated with this command引發的問題

C#.net mysql There is already an open datareader associated with this command引發的問題

關閉 close csdn != 定義 spa apt 因此 關鍵字

【參考】There is already an open datareader associated with this command引發的問題

我在語句中並未使用 DataReader,未何也提示同樣的錯誤,這個DataReader隱藏在哪裏,我給大家在這裏指出來,由於本人研究的還不夠深入,只知道有一種方法的調用後會生成 DataReader,我想這也是絕大多數人遇到頭疼的問題。

在使用數據庫更新或插入語句時,大家通常使用 SqlCommand 的 ExecuteNonQuery() 方法,並且前提是定義了一個公共的數據庫連接(如果每次查詢時都生成新連接的話不會存在這個問題,但那樣數據庫占用的資源相對會高很多),在ExecuteNonQuery() 後,內部會生成一個空的 DataReader 對象,並當當前的數據庫連接關閉掉後,該 DataReader 才會釋放。因此在大家使用更新方法時,推薦使用 using 關鍵字,它作為語句,可以將它所定義範圍內的對象都釋放掉。

1、解決方法是在ConnectionString中加上一個參數“MultipleActiveResultSets”, 將其值設置為true。X

server=192.168.9.24;database=FLGL;user=sa;password=1231q2w34;MultipleActiveResultSets=true

2、連接未關閉。 連接的當前狀態為正在連接。

using (FLGLConn = new SqlConnection(FLGLConnStr))
{
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procName;
if (paramArray != null)
cmd.Parameters.AddRange(paramArray);
try
{
//用SqlDataAdapter 就不必寫conn.open()和conn.close(),這是多余的。
cmd.Connection = FLGLConn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
}
catch (Exception ex)
{
Log.WriteErrorLog(ex.Message + ex.Source + " -- sql 語句為:" + procName);
}
finally
{
FLGLConn.Close();
}
return ds;
}

C#.net mysql There is already an open datareader associated with this command引發的問題