0

我正在尝试创建一种方法,可以在其中执行 mysql UPDATE、DELETE 或 INSERT 查询。该方法必须在使用我询问或不询问的 INSERT 时起作用last_insert_id()。以下是我目前拥有的代码:

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();
  }
}

这样做的问题是,当我使用返回 a 的插入查询时,last_insert_id()该方法效果很好。但是当查询不返回时last_insert_id(),方法就会出现故障。我怎样才能让这个方法起作用?

4

1 回答 1

0

为什么不使用 OUTPUT 参数,它将返回最后插入的 id。 Sql参数

如果你知道 LastInsertID 什么时候可以生成,那么你可以再向方法传递一个参数,告诉它正在检索插入的 ID,基于该参数你可以做一些这样的事情。

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

于 2012-04-01T11:55:39.997 回答