简体   繁体   中英

How to get TableAdapters to properly run an insert and then a SELECT_LAST_ID()

Sniplet:

    int resNo = -1;
    MoviesTableAdapters.reservationTableAdapter resAdapter = new MoviesTableAdapters.reservationTableAdapter();
    if (Int32.TryParse(info[1], out phoneNo))
    {
    resNo = resAdapter.InsertQuery(phoneNo, info[0]);
    }

Running this I keep getting 1 as a return, even though my LAST_INSERT_ID() is something different.

My query is like this

INSERT INTO `reservation` (`phone_no`, `password`) VALUES (@phone_no, @password);
SELECT LAST_INSERT_ID() FROM reservation;

The obvious conclusion here is that the return of the integer didn't work, but no matter what I initialize resNo to, I still get 1 - when I run it in my website, when I run it directly against the MySQL database I get the correct ID.

This has lead me to the conclusion, that it is either me who're using the TableAdapter wrong/misunderstood how it works.

Thanks in advance for any answers.

Here's what I think not 100% sure.

Why does it not work in the website
In your website each new query gets to use a new connection.

last_insert_id() only returns the last_id of the current connection.
Since query1: insert ... uses a different connection from query2: select last_insert_id() query2 will always return 1.

And why does it work ok in the database
Running directly against the database, the database is clever enough to keep the same connection open and query1 and query2 run in the same connection.

What to do about it
You need to research how to force your c# code to use persistent connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM