簡體   English   中英

插入SqlLite需要太長時間

[英]inserting to SqlLite takes too long

我插入這樣的數據,但它需要太長時間

對於34,000條記錄,花了20分鍾! (例如,如果我插入SQL Server CE只花了3分鍾)

conn_sql = new SQLiteConnection(conn_str2);
conn_sql.Open();
cmd_sql = conn_sql.CreateCommand();

for (int i = 0; i < iTotalRows; i++)
{
    try 
    { 
        Makat = dsView.Tables["Items"].Rows[i]["Makat"].ToString().Trim(); 
    }
    catch { Makat = ""; }

    try 
    { 
        Barcode = dsView.Tables["Items"].Rows[i]["Barcode"].ToString().Trim(); 
    }
    catch { Barcode = ""; }

    try 
    { 
        Des = dsView.Tables["Items"].Rows[i]["Des"].ToString().Trim(); 
    }
    catch { Des = ""; }

    try 
    { 
         Price = dsView.Tables["Items"].Rows[i]["Price"].ToString().Trim(); 
    }
    catch { Price = ""; }

    SQL = "INSERT INTO Catalog(Makat,Barcode,Des,Price)VALUES('" + Makat + "','" + Barcode + "','" + Des + "','" + Price + "')";
    cmd_sql.CommandText = SQL;
    cmd_sql.CommandType = CommandType.Text;

    cmd_sql.ExecuteNonQuery();

    //cmd_sql.Dispose();
}

如何插入更快?

SQLite隱式地在事務中包裝查詢。 在循環中開始和提交事務可能會減慢速度。 我認為如果你啟動一個事務並在循環完成后提交它,你應該大大提高速度:

conn_sql.Open();
using(var tran = conn_sql.BeginTransaction()) // <--- create a transaction
{
     cmd_sql = conn_sql.CreateCommand();
     cmd_sql.Transaction = tran;   // <--- assign the transaction to the command
              
     for (int i = 0; i < iTotalRows; i++)
     {
          // ...
          cmd_sql.CommandText = SQL;
          cmd_sql.CommandType = CommandType.Text;
          cmd_sql.ExecuteNonQuery();
          //cmd_sql.Dispose();

     }
     tran.Commit(); // <--- commit the transaction
} // <--- transaction will rollback if not committed already

首先,嘗試使用StringBuilder進行字符串連接。 其次,您正在發出34k請求,這很慢,嘗試減少請求量。 假設使用StringBuilder將5k插入語句連接在一起並在事務中觸發,執行此操作直到所有數據都不會被保存。

如果你在一次交易中這樣做,它應該更快:

SqlTransaction transaction;
try
{
    conn_sql = new SQLiteConnection(conn_str2);
    conn_sql.Open();
    cmd_sql = conn_sql.CreateCommand();

    transaction = conn_sql.BeginTransaction();

    for (int i = 0; i < iTotalRows; i++)
    {
        // create SQL string
        cmd_sql.CommandText = SQL;
        cmd_sql.CommandType = CommandType.Text;
        cmd_sql.ExecuteNonQuery();
    }

    transaction.Commit();
}
catch
{
    transaction.Rollback();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM