C# 在打开的DataReader中执行另一条MySQL语句

C# 在打开的DataReader中执行另一条MySQL语句,c#,mysql,sql,wpf,C#,Mysql,Sql,Wpf,我有一个WPF应用程序,它使用MySQL连接来处理数据库。我有一个特定的查询,用于检查我的输入信息是否具有数据库中已经存在的唯一id。如果有,那么我什么也不需要做,但如果没有,我需要在那里插入一条新记录。 下面是我的代码。问题是,在我尝试创建和执行新命令的最后一个using语句中,我得到一个错误,说“已经有一个打开的DataReader与此连接存在。” 从外观上看,我需要建立一个不同的连接并使用它,但是使用当前连接有解决办法吗 using (MySqlCommand checkCmd = co

我有一个WPF应用程序,它使用MySQL连接来处理数据库。我有一个特定的查询,用于检查我的输入信息是否具有数据库中已经存在的唯一id。如果有,那么我什么也不需要做,但如果没有,我需要在那里插入一条新记录。 下面是我的代码。问题是,在我尝试创建和执行新命令的最后一个using语句中,我得到一个错误,说“已经有一个打开的DataReader与此连接存在。”

从外观上看,我需要建立一个不同的连接并使用它,但是使用当前连接有解决办法吗

 using (MySqlCommand checkCmd = con.CreateCommand())
 {
     checkCmd.CommandText = "SELECT id FROM table WHERE id = @RFID";
     checkCmd.Parameters.AddWithValue("RFID", myValue);

     using (MySqlDataReader reader = checkCmd.ExecuteReader())
     {
         //if not found, then insert the new value in the database
         if (!reader.Read())
         {
              using (MySqlCommand cmd = con.CreateCommand())
              {
                  //try to create and execute insert query here
              }
         }
     }
}

在您的示例中,您可以简单地关闭阅读器并进行插入

bool found;

using (MySqlCommand checkCmd = con.CreateCommand())
{
    checkCmd.CommandText = "SELECT id FROM table WHERE id = @RFID";
    checkCmd.Parameters.AddWithValue("RFID", myValue);

    using (MySqlDataReader reader = checkCmd.ExecuteReader())
    {
        found = reader.Read();
    }
}

if(!found) {
    using (MySqlCommand cmd = con.CreateCommand())
    {
        //try to create and execute insert query here
    }
}

如果
id
被认为是唯一的,另一个可能的选项是根本不进行选择,只需在
id
上设置一个唯一索引,并使用
INSERT IGNORE
插入行(如果行不存在)。

在示例中,您可以简单地关闭读卡器并进行插入

bool found;

using (MySqlCommand checkCmd = con.CreateCommand())
{
    checkCmd.CommandText = "SELECT id FROM table WHERE id = @RFID";
    checkCmd.Parameters.AddWithValue("RFID", myValue);

    using (MySqlDataReader reader = checkCmd.ExecuteReader())
    {
        found = reader.Read();
    }
}

if(!found) {
    using (MySqlCommand cmd = con.CreateCommand())
    {
        //try to create and execute insert query here
    }
}

如果假定
id
是唯一的,另一个可能的选项是根本不进行选择,只需在
id
上设置一个唯一索引,并使用
INSERT IGNORE
插入行(如果行不存在)。

另一个选项是创建一个过程,该过程将像

create procedure insertifnotexist @rfid int,@someothercolumn varchar(10)
as
begin
declare @tabid int;
SELECT @tabid = id FROM table WHERE id = @rfid;
if(@tabid = '')
insert into table values(@rfid,@someothercolumn);
end

然后从代码中调用此过程,并传递@RFID参数。

另一个选项是创建一个过程,该过程将像

create procedure insertifnotexist @rfid int,@someothercolumn varchar(10)
as
begin
declare @tabid int;
SELECT @tabid = id FROM table WHERE id = @rfid;
if(@tabid = '')
insert into table values(@rfid,@someothercolumn);
end

然后从代码调用此过程,传递@RFID参数。

为什么不使用现有连接
con
,不创建另一个
cmd
?尝试使用dataset/dataadapter(或)创建一个过程,该过程将一次完成所有任务。为什么不使用现有连接
con
,不要创建另一个
cmd
?尝试使用dataset/dataadapter(或)创建一个过程,该过程将一次完成所有任务。