Prepared statements

from the Artful MySQL Tips List


To prepare & execute a parameterised SQL statement:
  • If a connection is not available, open one
  • Pass the command string and the connection object to the MySqlCommand constructor
  • Call MySqlCommand.Prepare;
  • Add the parameter to MySqlCOmmand.parameters
  • Set its value
  • call MySqlCommand.ExecuteNonQuery
try {
  MySqlConnection conn = 
    new MySqlConnection("Server=SRVR;uid=USR;pwd=PWD;database=DB");
  conn.Open();
  MySqlCommand insCmd = new MySqlCommand( "INSERT INTO tbl VALUES(NULL, ?id)", conn );
  insCmd.Prepare();
  insCmd.Parameters.Add( 
    new MySqlParameter( "?id", MySqlDbType.VarChar ));
  insCmd.Parameters[0].Value = "X";
  int ret = insCmd.ExecuteNonQuery();
}
catch( MySqlException e )  {
  MessageBox.Show( e.Message + Environment.NewLine + e.StackTrace.ToString() );
}

Last updated 22 May 2009


Return to the Artful MySQL Tips page