简体   繁体   English

C#MySQL一返回last_insert_id

[英]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. 我正在尝试创建一种方法,在该方法中可以执行mysql UPDATE,DELETE或INSERT查询。 The method must work when with an INSERT I ask or do not ask the last_insert_id() . 当我询问或不询问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. 问题是,当我使用返回last_insert_id()的插入查询时,该方法可以last_insert_id()地工作。 But when the query doesn't return an last_insert_id() the method malfunctions. 但是,当查询未返回last_insert_id()该方法将失败。 How can I get this method to work? 如何使这种方法起作用?

why not u use OUTPUT parametres, it will return the last inserted id. 为什么不使用OUTPUT参数,它将返回最后插入的ID。 SqlParamet 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 . 并且如果您知道LastInsertID何时可以生成,则可以将另一个参数传递给method,以告知它正在检索insertedID,您可以基于该参数执行以下操作。

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 PS:您需要对其进行更多调整以获得更好的效率,因为我给出了一些基本的想法,我们如何在不使用参数的情况下做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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