我有以下代码,我得到例外:
已经有一个
DataReader
与此相关的开放Connection
,必须先关闭.
我在这个项目中使用Visual Studio 2010/.Net 4.0和MySQL.基本上我在尝试使用数据读取器执行其他任务时运行另一个SQL语句.我正在排队cmdInserttblProductFrance.ExecuteNonQuery();
SQL = "Select * from tblProduct";
//Create Connection/Command/MySQLDataReader
MySqlConnection myConnection = new MySqlConnection(cf.GetConnectionString());
myConnection.Open();
MySqlCommand myCommand = new MySqlCommand(SQL, myConnection);
MySqlDataReader myReader = myCommand.ExecuteReader();
myCommand.Dispose();
if (myReader.HasRows)
{
int i = 0;
// Always call Read before accessing data.
while (myReader.Read())
{
if (myReader["frProductid"].ToString() == "") //there is no productid exist for this item
{
strInsertSQL = "Insert Into tblProduct_temp (Productid) Values('this istest') ";
MySqlCommand cmdInserttblProductFrance = new MySqlCommand(strInsertSQL, myConnection);
cmdInserttblProductFrance.ExecuteNonQuery(); //<=====THIS LINE THROWS "C# mySQL There is already an open DataReader associated with this Connection which must be closed first."
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jos*_* M. 25
总是,总是将一次性对象放在using语句中.我看不出你是如何实例化你的DataReader但你应该这样做:
using (Connection c = ...)
{
using (DataReader dr = ...)
{
//Work with dr in here.
}
}
//Now the connection and reader have been closed and disposed.
Run Code Online (Sandbox Code Playgroud)
现在,为了回答您的问题,读者使用与您尝试的命令相同的连接ExecuteNonQuery
.您需要使用单独的连接,因为DataReader会保持连接打开并根据需要读取数据.
Bro*_*ass 10
您正尝试在ExecuteNonQuery()
此读取器已使用的SQL连接上插入(with ):
while (myReader.Read())
Run Code Online (Sandbox Code Playgroud)
首先读取列表中的所有值,关闭阅读器然后执行插入,或使用新的SQL连接.
小智 9
只需MultipleActiveResultSets=True
在您的连接字符串中使用。
小智 8
添加MultipleActiveResultSets=true
到文件 appsettings.json 中连接字符串示例的提供程序部分
"ConnectionStrings": {
"EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=YourDatabasename;Trusted_Connection=true;MultipleActiveResultSets=true"}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
96313 次 |
最近记录: |