以下代码需要2分钟左右的时间才能删除3万条记录,我确信这太长了。我在这里看到的大多数类似问题都可以通过使用SQLiteTransaction
对象来解决,但我已经做到了。
private void removeProxiesButton_Click(object sender, EventArgs e)
{
using (var conn = new SQLiteConnection(Properties.Settings.Default.dbConnectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
using (var cmd = new SQLiteCommand("DELETE FROM Proxy WHERE IP=@ip AND Port=@port", conn, trans))
{
foreach (DataGridViewRow row in proxiesDataGridView.SelectedRows)
{
var proxy = proxies[row.Index];
cmd.Parameters.AddWithValue("@ip", proxy.IP);
cmd.Parameters.AddWithValue("@port", proxy.Port);
cmd.ExecuteNonQuery();
proxies.Remove(proxy);
}
}
trans.Commit();
}
}
}
这是CREATE
表的Proxy
语句。
CREATE TABLE "Proxy"
(
`ProxyID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`Status` TEXT,
`IP` TEXT,
`Port` INTEGER,
`Country` TEXT,
`Speed` INTEGER,
`DateAdded` TEXT
)
答案 0 :(得分:0)
使用StringBuilder构建一个长的SQLite语句,并且仅执行一次SQLiteCommand对象会大大加快工作速度。
private void removeProxiesButton_Click(object sender, EventArgs e)
{
using (var conn = new SQLiteConnection(Properties.Settings.Default.dbConnectionString))
{
conn.Open();
var sb = new StringBuilder();
sb.Append("DELETE FROM Proxy WHERE ProxyID IN (");
foreach (DataGridViewRow row in proxiesDataGridView.SelectedRows)
{
var proxy = proxies[row.Index];
sb.Append(proxy.ProxyID + ",");
}
sb[sb.Length - 1] = ')';
using (var cmd = new SQLiteCommand(sb.ToString(), conn))
{
cmd.ExecuteNonQuery();
}
}
}