Reputation: 101
I have looked around and I am still confused on how to get the last inserted ID. I added the statment SELECT LAST_INSERT_ID();
at the end of mysql statement i am executing. I am storing the value in prID = Convert.ToInt32(cmd.ExecuteScalar());
This command is creating two instances in my database. I am pretty sure I need to separate these two statements but unsure how to while still getting the last ID.
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "INSERT INTO pull_requests (repoID, branchID, fileID, prStatus, prComments) VALUES (@rID, @bID, @fID, @prS, @prC); SELECT LAST_INSERT_ID();";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@rID", RI);
cmd.Parameters.AddWithValue("@bID", BI);
cmd.Parameters.AddWithValue("@fID", FI);
cmd.Parameters.AddWithValue("@prS", 0);
cmd.Parameters.AddWithValue("@prC", comment);
prID = Convert.ToInt32(cmd.ExecuteScalar());
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Upvotes: 1
Views: 2195
Reputation: 3166
You need to only call cmd.ExecuteNonQuery()
to execute the insert statement. On the return, the cmd
object will have its .LastInsertedId
property populated for you.
Like this:
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "INSERT INTO pull_requests (repoID, branchID, fileID, prStatus, prComments) VALUES (@rID, @bID, @fID, @prS, @prC);";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@rID", RI);
cmd.Parameters.AddWithValue("@bID", BI);
cmd.Parameters.AddWithValue("@fID", FI);
cmd.Parameters.AddWithValue("@prS", 0);
cmd.Parameters.AddWithValue("@prC", comment);
cmd.ExecuteNonQuery();
long lastId = cmd.LastInsertedId;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Upvotes: 6
Reputation: 15951
Typically, the SELECT last_insert_id() is executed separately, immediately after the INSERT is executed, on the same connection. The result of last_insert_id() is connection specific, so you do not need to worry about other clients "overwriting" yours.
You can even reuse the same command with just cmd.CommandText = "SELECT last_insert_id()";
...but as others have pointed out, and a quick web search has clarified for me, it looks like the MySQL .Net connector you are using already provides that without a second query.
Upvotes: 1
Reputation: 314
Use the MySqlCommand.LastInsertedId
property after executing the query.
Upvotes: 3