gpt4 book ai didi

c# - 为什么 SQLite 插入会非常慢? (使用的交易)

转载 作者:行者123 更新时间:2023-12-03 01:57:29 30 4
gpt4 key购买 nike

我正在 SQLite 数据库中插入 8500 行。在 Core 2 Duo 上需要> 30sec。这段时间CPU使用率达到了70%,那么问题就出在CPU使用率上了。

我正在使用事务。

我在临时文件中动态创建数据库、表和插入。那我就不用担心腐败等问题了。

我只是尝试使用这个,但没有帮助:

PRAGMA journal_mode = OFF;
PRAGMA synchronous = OFF;

我还能做什么?

如果我在 Firefox SQLite 管理器插件中运行相同的脚本,它会立即运行。

我运行探查器。

所有时间都在

27seg System.Data.SQLite.SQLite3.Prepare(SQLiteConnection, String, SQLiteStatement, UInt32, String&)

该方法调用了三个方法

12seg System.Data.SQLite.SQLiteConvert.UTF8ToString(IntPtr, Int32)
9seg System.Data.SQLite.SQLiteConvert.ToUTF8(String)
4seg System.Data.SQLite.UnsafeNativeMethods.sqlite3_prepare_interop(IntPtr, IntPtr, Int32, IntPtr&, IntPtr&, Int32&)

您要求显示插页。这里:

INSERT INTO [Criterio] ([cd1],[cd2],[cd3],[dc4],[dc5],[dt6],[dc7],[dt8],[dt9],[dt10],[dt11])VALUES('FFFFFFFF-FFFF-FFFF-FFFF-B897A4DE6949',10,20,'',NULL,NULL,'',NULL,julianday('2011-11-25 17:00:00'),NULL,NULL);

表:

CREATE TABLE Criterio (
cd1 integer NOT NULL,
cd2 text NOT NULL,
dc3 text NOT NULL,
cd4 integer NOT NULL,
dt5 DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
dt6 DATE NULL,
dt7 DATE NULL,
dc8 TEXT NULL,
dt9 datetime NULL,
dc10 TEXT NULL,
dt11 datetime NULL,
PRIMARY KEY (cd2 ASC, cd1 ASC)

);

C# 代码:

        scriptSql = System.IO.File.ReadAllText(@"C:\Users\Me\Desktop\ScriptToTest.txt");

using (DbCommand comando = Banco.GetSqlStringCommand(scriptSql))
{
try
{
using (TransactionScope transacao = new TransactionScope())
{
Banco.ExecuteNonQuery(comando);
transacao.Complete();
}
}
catch (Exception ex)
{
Logging.ErroBanco(comando, ex);
throw;
}
}

最佳答案

我不知道为什么 pst 删除了他的答案,因此我将重新发布其中的相同信息,因为这似乎是正确的答案。

根据 SQLite 常见问题解答 - INSERT is really slow - I can only do few dozen INSERTs per second

Actually, SQLite will easily do 50,000 or more INSERT statements per second on an average desktop computer. But it will only do a few dozen transactions per second

...

By default, each INSERT statement is its own transaction. But if you surround multiple INSERT statements with BEGIN...COMMIT then all the inserts are grouped into a single transaction.

所以基本上您需要将 INSERT 分组为更少的事务。

更新:所以问题可能主要是由于 SQL 脚本的巨大大小 - SQLite 需要在执行之前解析整个脚本,但解析器将被设计为解析小脚本不是大的!这就是为什么您会看到在 SQLite3.Prepare 方法中花费了如此多的时间。

相反,您应该使用参数化查询并在 C# 代码中的循环中插入记录,例如,如果您的文本文件中的数据采用 CSV 格式,则可以使用如下内容:

using (TransactionScope txn = new TransactionScope())
{
using (DbCommand cmd = Banco.GetSqlStringCommand(sql))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
// Set the parameters for the command at this point based on the current line
Banco.ExecuteNonQuery(cmd);
txn.Complete();
}
}
}

关于c# - 为什么 SQLite 插入会非常慢? (使用的交易),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8339919/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com