convert commandtext to string problem in answered question
Question Related to this post, I think he is offline tho so I cant get any feedback atm: MySql and inserting last ID problem remains Im not sure if im being completely blind but in this code:
// run the insert using a non query call
command.CommandText = cmd.ToString();
command.ExecuteNonQuery();
/* now we want to make a second call to MYSQL to get the new index
value it created for the primary key. This is called using scalar so it will
return the value of the SQL statement. We convert that to an int for later use.*/
command.CommandText = "select last_insert_id();";
id = Convert.ToInt32(command.ExecuteScalar());
//------- the name id does not exist in the 开发者_开发技巧current context
// Commit the transaction.
transaction.Commit();
}
catch (Exception ex)
{
Label10.Text = ": " + ex.Message;
try
{
// Attempt to roll back the transaction.
transaction.Rollback();
}
catch
{
// Do nothing here; transaction is not active.
}
}
}
id isnt set to anything and im not sure how he was trying to set it to the last inserted id?
EDIT:
int id = Convert.ToInt32(cmd.ExecuteScalar());
Label10.Text = Convert.ToString(id);
You should be able to return the id of the inserted record using select @@IDENTITY;
without having to use a second query:
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); select @@IDENTITY;"
int id = Convert.ToInt32(cmd.ExecuteScalar());
After reviewing your old question, this should work the same:
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); SELECT LAST_INSERT_ID();"
int id = Convert.ToInt32(cmd.ExecuteScalar());
精彩评论