Question

I have an ODBC example that connects to a MySQL database using the dsn DSN=RDBMSTest (I've created this to connect to my database.

I'm trying to find the Last inserted ID but I am not getting the last ID from my table.

Here is my code:

using System;
using System.Data.Odbc;

namespace TestClient
{
    class Program
    {
        private static OdbcCommand command;
        static void Main(string[] args)
        {
            // test odbc connection and get last insert id
            string dsn = "DSN=RDBMSTest";
            using(OdbcConnection connection = new OdbcConnection(dsn))
            {
                connection.Open();
                OdbcTransaction transaction = null;
                command = new OdbcCommand();
                try
                {
                    transaction = connection.BeginTransaction();
                    command.Connection = connection;
                    command.Transaction = transaction;
                    command.CommandText = "SELECT * FROM test.new_table ORDER BY ID DESC";
                    command.ExecuteNonQuery();
                    command.CommandText = "SELECT last_insert_id()";
                    command.ExecuteNonQuery();
                    transaction.Commit();

                    OdbcDataReader reader = command.ExecuteReader();
                    while(reader.Read())
                    {
                        for(int i = 0; i < reader.FieldCount; i++)
                        {
                            Console.WriteLine(reader.GetName(i) + ": " + reader.GetValue(i));
                        }
                    }
                    reader.Close();
                    transaction.Dispose();
                    command.Dispose();
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            Console.Read();
        }
    }
}

I am getting an ID of 0 and my last ID should be 186 according to the table (test_table) I am using.

Was it helpful?

Solution

last_insert_id() applies to INSERT queries only. The last insert performed by a particular connection. It will not report on inserts done in other connections, it will not report on inserts you did with your account 10 days ago.

You're not doing an insert, just a SELECT.

You need to use SELECT MAX(id) instead... and note that this is highly racy. If you're using it to generate client-side IDs, don't. Another parallel client can swoop in behind your back and steal away the ID you're generating, or create an even newer/bigger ID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top