我有两个 DataTables
DataTable dtDataForTransactions;
DataTable dtDataForTransline;
在我的C#代码中。 dtDataForTransline
可以针对dtDataForTransactions
中的任何交易提供单个或多个记录。例如
dtDataForTransactions
transid | ticketid | storeid | TIMESTAMP | transtypeid | total
----------------------------------------------------------------
A-101 | 101 | 1 | 20018-03-23 | 1 |60.00
A-102 | 102 | 1 | 20018-03-23 | 1 |30.25
A-103 | 103 | 1 | 20018-03-23 | 1 |75.50
dtDataForTransline
transid | productid | qty | price
---------------------------------
A-101 | 1000001 | 1 |60.00 // single trnsline against transaction
// two entry against one A-102 transaction
A-102 | 1054141 | 1 |20.25
A-102 | 5421441 | 2 |10.00
// three entries for A-103 transaction
A-103 | 1088888 | 1 |20.50
A-103 | 5435415 | 3 |15.00
A-103 | 9921441 | 6 |40.00
如果发生意外事件,我正在使用事务滚动。我目前插入数据的方式需要很长时间(例如,事务表中的5条记录为15秒,透射表中有15条记录)。
如何使其高效,我的MySql数据库在云端,我正在从本地机器上打这个电话。
我的代码:
using (MySqlConnection con = new MySqlConnection(connectionMySql))
{
con.Open();
foreach (DataRow row in dtDataForTransactions.Rows)
{
try
{
tr = con.BeginTransaction();
MySqlCommand cmd = new MySqlCommand();
cmd = new MySqlCommand("INSERT INTO transaction (transid, ticketid, storeid, TIMESTAMP, transtypeid, total) Values (@transid, @ticketid, @storeid, @timestamp, @transtypeid, @total)", con, tr);
cmd.Parameters.Add(new MySqlParameter("@transid", row["transid"])).MySqlDbType = MySqlDbType.VarChar;
cmd.Parameters.Add(new MySqlParameter("@ticketid", row["ticketid"])).MySqlDbType = MySqlDbType.VarChar;
cmd.Parameters.Add(new MySqlParameter("@storeid", row["storeid"])).MySqlDbType = MySqlDbType.Int32;
cmd.Parameters.Add(new MySqlParameter("@timestamp", row["TIMESTAMP1"])).MySqlDbType = MySqlDbType.DateTime;
cmd.Parameters.Add(new MySqlParameter("@transtypeid", row["transtypeid"])).MySqlDbType = MySqlDbType.Int32;
cmd.Parameters.Add(new MySqlParameter("@total", row["total"])).MySqlDbType = MySqlDbType.Float;
cmd.ExecuteNonQuery();
DataTable dtTemp = dtDataForTransline.AsEnumerable().
Where(s => s.Field<string>("transid") == row["transid"].ToString()).CopyToDataTable();
foreach (DataRow row2 in dtTemp.Rows)
{
cmd = new MySqlCommand("INSERT INTO transline (transid,productid,qty,price) values (@transid, @productid, @qty, @price)", con, tr);
cmd.Parameters.Add(new MySqlParameter("@transid", row2["transid"])).MySqlDbType = MySqlDbType.VarChar;
cmd.Parameters.Add(new MySqlParameter("@productid", row2["barcode"])).MySqlDbType = MySqlDbType.VarChar;
cmd.Parameters.Add(new MySqlParameter("@qty", row2["qty"])).MySqlDbType = MySqlDbType.Double;
cmd.Parameters.Add(new MySqlParameter("@price", row2["price"])).MySqlDbType = MySqlDbType.Decimal;
//cmd.Parameters.Add(new MySqlParameter("@transid1", row["transid"])).MySqlDbType = MySqlDbType.VarChar;
cmd.ExecuteNonQuery();
}
tr.Commit();
cmd.Dispose();
}
catch (Exception ex)
{
tr.Rollback();
lblMessage.Text = ex.Message;
break;
}
}