开发者

Catch Id (INT AUTO INCREMENT) of a Record after INSERT INTO Statement

开发者 https://www.devze.com 2022-12-13 13:58 出处:网络
This is my first time I use MySQL as datastora开发者_如何学JAVAge for my C# Application, as I\'ve seen that there is no UNIQUEIDENTIFIER type as in SQL server I decieded to use INT with AUTO_INCREMENT

This is my first time I use MySQL as datastora开发者_如何学JAVAge for my C# Application, as I've seen that there is no UNIQUEIDENTIFIER type as in SQL server I decieded to use INT with AUTO_INCREMENT, my problem is now if I execute a INSERT, how may I get the ID of the Record I just added.

My quick and dirty solution has been to execute a SELECT MAX(ID) FROM table Statement. But this doesn't seem consistent. I belive there is a better solution something like mysql_insert_id() (PHP).

Any Idea how to resolve this in C#?


You use the function last_insert_id() in a query to get the last created id:

select last_insert_id()

You have to use the same database session, i.e. the same connection object.

As you have figured out, you should not use select max(id) to get the id, as that will get the last id created by any session, not this specific session. If two inserts are done for separate users close in time (so that both inserts happen before one of them do the select to get the id), they will both get the id of the last insert.


The solution of Guffa is a possibility, thanks for this, but I figured out that I can use also LastInsertedId on my Command, a short example:

MySqlCommand cmd = new MySqlCommand("INSERT INTO users (Username, Prename, Lastname, Password) VALUES (\"" +
                                            user.Username + "\",\"\", \"\",\"\")", new MySqlConnection(u.ConnectionString()));
        cmd.CommandType = CommandType.Text;
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        long id = cmd.LastInsertedId;

But this doesn't work if the command executes a Stored Procedure.

Regards, Johannes

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号