Click here to Skip to main content
16,004,587 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
MySqlConnection connection = new MySqlConnection("datasource=123.456.789 ;port=3306;username=blabla ;password=blabla");
MySqlCommand command;
MySqlDataReader mdr;


connection.Open();
string selectQuery = "SELECT_LAST_INSERT_ID() * FROM mysqlcshap.Alamierung";
command = new MySqlCommand(selectQuery, connection);
mdr = command.ExecuteReader();
if (mdr.Read())

What I have tried:

How can i fix this?



SELECT_LAST_INSERT_ID() * FROM 
Posted
Updated 30-Jul-18 6:32am
Comments
Dave Kreskowiak 30-Jul-18 12:02pm    
Why would you want to?
Patrice T 30-Jul-18 12:23pm    
What do you want to do with this ID ?

Simple: don't.
It's not relevant at all, and particularly the way you are using it, or planning to use it.

The problem is that MySql is by its very nature a Multiuser system - which gives you problems if you try to use the last ID value, regardless of what you want to use it for.

If you want to use it to access the data you just created, you can't do it reliably like that as the value you get may not be relevant to your user - it could well have been created by a totally different user. The only way to get the ID that you wanted is to SELECT it as part of the INSERT operation using the LAST_INSERTED_ID[^] function as part of teh same command, or at the very, very least same connection.

If you want to use it to provide a "next ID" value by adding one to it before you actually do an INSERT, that's even more dangerous, because you have no way of knowing how long it will be before you use it, and that ID can have been used by numerous other users already and your database integrity completely compromised as a result.

You never need an ID value until a row is inserted, and any system which relies on "predicting" ID values is going to fail in production in some really, really nasty ways.

If you are trying to use automatic ID values to provide foreign keys, then I'd strongly suggest you use GUID ID values instead, so you have control over what is going on. The row ID should not be used as a userID or customerID at all...
 
Share this answer
 
Comments
Eric Lynch 30-Jul-18 13:11pm    
OriginalGriff, as usual, provides sage advice here. I'd add one item, in case you need to generate an identity. In addition to GUIDs, MySQL also supports AUTO_INCREMENT columns, see: https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
Try this:

SQL
SELECT MAX(ID) AS LastInsertedID;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900