views:

27

answers:

0

I'm using asp.net and MySql to insert data into a table using transaction. I loop through a list of items and inserts them to the table.

This code runs quite often and the problem I am having is that sometimes when I insert data one of my parameters is null when inserted into the database but it shouldn't be null. I have started logging the parameter and it has the right value before the insert but the right value is not inserted into the table.

I cannot figure out what goes wrong, maybe you can see something wrong with my code? Can the problem has something to do with using transactions?

I have tried to reproduce the problem but can't figure out when it is happening. I'm glad for all the help I can get, thanks a lot!

This is the code I'm using:

    MySqlConnection mysqlconn = new MySqlConnection("...");
    mysqlconn.Open();
    MySqlCommand mysqlcmd = new MySqlCommand();
    mysqlcmd.Connection = mysqlconn;
    using (MySqlTransaction mysqltransaction = mysqlconn.BeginTransaction())
    {
        using (mysqlcmd)
        {
            MySqlParameter id = new MySqlParameter("?id", MySqlDbType.Int32);
            mysqlcmd.Parameters.Add(id);

            foreach (Item item in list)
            {
                id.Value = item.id;
                LogTheId(id.Value); //<--- I log the id here and it is 99 like it should be

                sql = @"INSERT INTO parenttable (title) VALUES ('test'); 
                INSERT INTO table (id,parentid,otherid) VALUES (?id,LAST_INSERT_ID(),(SELECT otherid FROM othertable WHERE othertable.id=?id));";

                mysqlcmd.CommandText = sql;
                mysqlcmd.ExecuteNonQuery();
            }
        }
        mysqltransaction.Commit(); //<--- When I commit the transaction and the id is written to table the id is sometimes NULL for some reason
    }
    mysqlconn.Close();