I have to copy more than 100k records in the same table and after every row insert in first table, second table will be updated with first table insert ID (Primary key). I tried to do bulk insert but then I would not get all the inserted ids which will be inserted in second table. I am using MySQL 5.5. When I run the following code, I get following random errors:
- Lost connection to MySQL server during query.
- The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements.
- Net packets out of order: received[x], expected[y].
How can I insert these records optimally?
CODE;
foreach (var item in transactions) { int transactionId; using (MySqlCommand cm = DM.ConnectionManager.Conn.CreateCommand()) { cm.CommandType = System.Data.CommandType.Text; var commandText = @"INSERT INTO FirstTable SET column1=@column1;"; cm.CommandText = commandText; cm.Parameters.AddWithValue("@column1", item.column1); cm.ExecuteNonQuery(); transactionId = (int)cm.InsertId; } foreach (var item in item.TransactionDetails) { using (MySqlCommand cm = DM.ConnectionManager.Conn.CreateCommand()) { cm.CommandType = System.Data.CommandType.Text; var commandText = @"INSERT INTO SecondTable SET column1=@column1, column2=@column2;"; cm.CommandText = commandText; cm.Parameters.AddWithValue("@column1", item.column1); cm.Parameters.AddWithValue("@column2", item.column2); cm.ExecuteNonQuery(); } } }
C# Stackoverflow Bulk Insert XML into MySql DatabaseCASE WHENstatement..but I'd need to know more information in regards to what you are truly trying to update.