我使用下面的代码批量插入30000行(每次1000行)。它仍然没有那么快。在这个例子中Improve INSERT-per-second performance of SQLite?我可以看到他们只创建SqliteCommand
一次,然后重新循环它重置它并清除绑定。但是,我无法在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 ( );
}
答案 0 :(得分:11)
尝试将您的代码更改为以下内容:
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 ( );
}
基本上,在每个循环中,您现在只需更改参数的值,而不是构建一个全新的查询。但是,我不确定,您的表现是否真的会从中受益。你需要尝试一下。
答案 1 :(得分:-2)
您还可以尝试使用存储过程插入行。它应该比内联语句更快,特别是插入这么多行。