简体   繁体   中英

C# mysql one return last_insert_id

I am trying to create a method in which I can exequte mysql UPDATE, DELETE or INSERT query. The method must work when with an INSERT I ask or do not ask the last_insert_id() . Below is the code that I have at the moment:

public int executeUID(MySqlCommand msCommand)
{
  try
  {
    this.Open();

    msCommand.Connection = this.msCon;

    return int.Parse(msCommand.ExecuteScalar().ToString());
  }
  catch (MySqlException ex)
  {
    throw ex;
  }
  finally
  {
    this.Close();
  }
}

The problem with this is is that when I use an insert query that returns a last_insert_id() the method works greatly. But when the query doesn't return an last_insert_id() the method malfunctions. How can I get this method to work?

why not u use OUTPUT parametres, it will return the last inserted id. SqlParamet

and if you know when LastInsertID can generate, then you can pass one more parameter to method, to tell that it is retriving insertedID, based on that parameter you can do some thing like this .

public int executeUID(MySqlCommand msCommand, bool Mode) //Mode==true means insertandRetriveLastID, false means =dont retrive last insertedit
{
  try
  {
    this.Open();

    msCommand.Connection = this.msCon;

    if(Mode)  //for getting last inserted id 
   {
      SqlParameter outParams= new SqlParameter("@ID", SqlDbType.Int);
      outParams.Direction =    ParameterDirection.Output;
      msCommand.Parameters.Add(outParams)
      msCommand.ExecuteNonQuery();
      var outputValue = cmd.Parameters["@ID"].Value;  
   }
    else //if no inserted id is not there 
    {
       return msComand.ExecuteNonQuery(); // it will return No of Rows Affected. 
    }

  }
  catch (MySqlException ex)
  {
    throw ex;
  }
  finally
  {
    this.Close();
  }
}

PS : you need to tune it some more for better efficiency, as i gave some basic ideas how we can do it with out parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM