Insert data and get last id


This technique is more described in this article MySQL .NET get ID of last inserted record

So here is just some code:

 

long lId = InsertMySQL_GetLast("test", 9);



        public long InsertMySQL_GetLast(string city, int country_id)
        {
            MySql.Data.MySqlClient.MySqlConnection oConn =
                new MySql.Data.MySqlClient.MySqlConnection("Database=sakila;Data Source=192.168.10.4;User id=stefan;Password=pekka");
            oConn.Open();


            MySql.Data.MySqlClient.MySqlCommand command =
                new MySql.Data.MySqlClient.MySqlCommand("insert into city(city, country_id ) select ?city, ?country_id; select LAST_INSERT_ID() ", oConn);

            command.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("?city", MySql.Data.MySqlClient.MySqlDbType.VarChar, 50));
            command.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("?country_id", MySql.Data.MySqlClient.MySqlDbType.Int16));
            command.Parameters[0].Value = city;
            command.Parameters[1].Value = country_id;
            long lNewId = (long)command.ExecuteScalar();

            oConn.Close();
            return lNewId;

        }