MySql.Data.MySqlClient.MySqlException'发生在MySql.Data.dll中 [英] MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll

查看:1281
本文介绍了MySql.Data.MySqlClient.MySqlException'发生在MySql.Data.dll中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从c#应用程序查询MySQL数据库.下面是代码,在这里我正在使用parameterized query

I am trying to query the MySQL database from a c# application. Below is the code , here I am using parameterized query

 public static void ValidateName(MySqlConnection conn,List<Employee> EmpList, string Group)
 {
   string selectQuery = "Select Name from Employee where Group = @Group  AND @Name in (FirstName, LastName);";
   using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
    {
     for (int i = 0; i < EmpList.Count; i++)
      {
        cmd.Parameters.Add("@Group", MySqlDbType.VarChar).Value = Group;
        cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
        var reader = cmd.ExecuteReader();
        List<string> lineList = new List<string>();
        while (reader.Read())
        {
            lineList.Add(reader.GetString(0));
        }
        if (lineList.Count <=0)
        {
           WriteValidationFailure(EmpList[i], "Failed");
        }
}       
}

但是上面的代码在下面一行说

But the above code is throwing error in below line saying

 cmd.Parameters.Add("@Group", MySqlDbType.VarChar).Value = Group;

类型为'MySql.Data.MySqlClient.MySqlException'的未处理异常 MySql.Data.dll'@Group中已经发生了

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll' @Group has already been defined

推荐答案

之所以发生这种情况,是因为您在每次迭代中都添加了相同的参数集.您可以在每次迭代中清除然后在启动循环之前添加它们,并在每次迭代期间更改现有参数的值.我认为第二种选择会很棒.我还要在此处指定关于阅读器的另一件事,您必须将阅读器用作using变量,以便每次将其放置在using块的末尾时,您的代码就可以正常工作.这意味着您可以尝试这样的事情:

This is happening because you are adding the same set of parameters in each iterations. You can either clear then in each iteration or else add them before starting the loop and change the value of existing parameter during each iteration. I think second option would be great. One more thing I have to specify here is about the reader, you have to use reader as an using variable so that each time it will get disposed at the end of the using block and your code works fine. Which means you can try something like this:

using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
    cmd.Parameters.Add(new MySqlParameter("@Group", MySqlDbType.VarChar));
    cmd.Parameters.Add(new MySqlParameter("@Name", MySqlDbType.VarChar));
    for (int i = 0; i < EmpList.Count; i++)
    {
        cmd.Parameters["Group"].Value = group;
        cmd.Parameters["Name"].Value = EmpList[i].Name;
        // rest of code here
       using (MySqlDataReader reader = cmd.ExecuteReader())
       {
           // Process reader operations 
       }

    }
}

这篇关于MySql.Data.MySqlClient.MySqlException'发生在MySql.Data.dll中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆