Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a method that accepts data and and is being called approx every second. I tried creating a parameterized query which inserts the results into a MySQL database table but I keep getting error messages telling me that the parameter has already been defined. Can someone please explain how this works and what I'm doing wrong? I've read the mysql doc on using prepared statements and it doesn't go in depth enough on using prepared statements.

C#
private void (string _fname, string _lname, string _age) 
{ 
string sql = "Insert Into myTbl (firstname,lastname,age) Values(@fname,@lname,@age)"; 
cmd.CommandText = sql; 
cmd.PrePare(); 
cmd.Parameters.AddWithValue("@fname", _fname); 
cmd.Parameters.AddWithValue("@lname", _lname); 
cmd.Parameters.AddWithValue("@age" , _age ); 

cmd.ExecuteNonQuery(); 
}
Posted
Updated 7-Feb-11 11:57am
v2
Comments
JOAT-MON 7-Feb-11 17:58pm    
EDIT - added code block

1 solution

Call cmd.Parameters.Clear() before you re-add the parameters. Or add a flag so that you only add them once (there is no need to re-add them each time).

C#
if(!parametersCreated)
{
  // add parameters here

  parametersCreated = true;
}


[Updated code based on our discussion via comments]
C#
private bool parametersCreated;

private void Foo(string _fname, string _lname, string _age)
{
  string sql = ". . .";
  cmd.CommandText = sql;

  cmd.Prepare();

  if(!parametersCreated)
  {
    // cmd.Parameters.Clear(); <-- No need for this now
    cmd.Parameters.AddWithValue("@fname", _fname);
    . . .

    parametersCreated = true;
  }
  else
  {
    cmd.Parameters["@fname"].Value = _fname;
    . . .
  }

  cmd.ExecuteNonQuery();
}
 
Share this answer
 
v5
Comments
Espen Harlinn 7-Feb-11 17:38pm    
Good answer :)
Nish Nishant 7-Feb-11 17:38pm    
Thanks.
d.allen101 7-Feb-11 17:40pm    
so that's it? just cmd.Parameters.Clear() and that's it?
Nish Nishant 7-Feb-11 17:49pm    
You need to call Clear if you have to re-create the parameters for some reason. Otherwise use the flag-technique I mentioned.
d.allen101 7-Feb-11 17:49pm    
THANKS Nishant!!!! I just tried in a demo app and it worked just fine!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900