mysql.data.dll error0,MySql.Data.MySqlClient.MySqlException'发生在MySql.Data.dll中

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 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 lineList = new List();

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;

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'

occurred in MySql.Data.dll' @Group has already been defined

解决方案

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

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值