gpt4 book ai didi

c# - 我怎样才能回收我的 SqliteCommand 来加速这个 Sqlite 批量插入 (iOS)?

转载 作者:IT王子 更新时间:2023-10-29 06:21:45 27 4
gpt4 key购买 nike

我正在使用下面的代码批量插入 30000 行(一次 1000 行)。它仍然没有那么快。在这个例子中 Improve INSERT-per-second performance of SQLite?我可以看到他们只创建了一次 SqliteCommand,然后将其重新设置为重置它并清除绑定(bind)。但是,我在 iOS/Monotouch 上找不到合适的方法。没有 Reset()ClearBindings() 或任何其他类似的东西。

using ( var oConn = new SqliteConnection ( "Data Source=" + DB_NAME ) )
{
oConn.Open ( );

// Wrap the whole bulk insertion into one block to make it faster, otherwise one transaction per INSERT would be created.
// Note that this is differen from "BEGIN TRANSACTION" which would increase memory usage a lot!
SqliteCommand oCmd = new SqliteCommand ( "BEGIN", oConn );
oCmd.ExecuteNonQuery ( );
oCmd.Dispose ( );

foreach ( MyObj oObj in aMyObjects )
{
oCmd = new SqliteCommand ( "INSERT INTO LocalObjects ( intID, intParentID, intObjectType, strName, dtModified VALUES (@intID, @intParentID, @intObjectType, @strName, @dtModified)", oConn );
oCmd.Parameters.AddWithValue ( "@intID", oMyObj.ID );
oCmd.Parameters.AddWithValue ( "@intParentID", oMyObj.ParentID );
oCmd.Parameters.AddWithValue ( "@intObjectType", ( int ) oMyObj.Type );
oCmd.Parameters.AddWithValue ( "@strName", oMyObj.Name );
oCmd.Parameters.AddWithValue ( "@dtModified", oMyObj.Modified );
oCmd.ExecuteNonQuery ( );
oCmd.Dispose ( );
}

oCmd = new SqliteCommand ( "END", oConn );
oCmd.ExecuteNonQuery ( );
oCmd.Dispose ( );

oConn.Close ( );
oConn.Dispose ( );
}

最佳答案

尝试将您的代码更改为以下内容:

using ( var oConn = new SqliteConnection ( "Data Source=" + DB_NAME ) )
{
oConn.Open ( );

// Wrap the whole bulk insertion into one block to make it faster, otherwise one transaction per INSERT would be created.
// Note that this is differen from "BEGIN TRANSACTION" which would increase memory usage a lot!
SqliteCommand oCmd = new SqliteCommand ( "BEGIN", oConn );
oCmd.ExecuteNonQuery ( );
oCmd.Dispose ( );

oCmd = new SqliteCommand ( "INSERT INTO LocalObjects ( intID, intParentID, intObjectType, strName, dtModified VALUES (@intID, @intParentID, @intObjectType, @strName, @dtModified)", oConn );

// <do this for all of your parameters>.
var id = oCmd.CreateParameter();
id.ParameterName = "@intID";
oCmd.Parameters.Add(id);
// </do this for all of your parameters>.

foreach ( MyObj oObj in aMyObjects )
{
// <do this for all of your parameters>.
id.Value = oMyObj.ID;
// </do this for all of your parameters>.

oCmd.ExecuteNonQuery ( );
}

oCmd.Dispose();

oCmd = new SqliteCommand ( "END", oConn );
oCmd.ExecuteNonQuery ( );
oCmd.Dispose ( );

oConn.Close ( );
oConn.Dispose ( );
}

基本上,在每个循环中,现在您只需更改参数的值,而不是构建一个全新的查询。但是,我不确定,您的表现是否真的会从中受益。您需要尝试一下。

关于c# - 我怎样才能回收我的 SqliteCommand 来加速这个 Sqlite 批量插入 (iOS)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5311897/

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