[英]C# mysql one return last_insert_id
我正在尝试创建一种方法,在该方法中可以执行mysql UPDATE,DELETE或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();
}
}
问题是,当我使用返回last_insert_id()
的插入查询时,该方法可以last_insert_id()
地工作。 但是,当查询未返回last_insert_id()
该方法将失败。 如何使这种方法起作用?
为什么不使用OUTPUT参数,它将返回最后插入的ID。 SqlParamet
并且如果您知道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:您需要对其进行更多调整以获得更好的效率,因为我给出了一些基本的想法,我们如何在不使用参数的情况下做到这一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.