[英]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.