我正在使用C#中的SQLite数据库。我必须在数据库中插入一个记录块。我的第一个版本只使用了自动生成的插入方法。但这需要大约一秒钟才能运行,而且对于客户来说这太慢了。所以我想我可以通过在程序段的开头和结尾以编程方式打开和关闭连接来优化它。
所以我有这样的事情:(我更改了变量名称)
try
{
tableAdapter.openInsertCommandConnection();
foreach (Data data in _data)
{
tableAdapter.InsertCommand(bytevalue, id1, id2);
}
}
finally
{
tableAdapter.closeInsertCommandConnection();
}
和
private ConnectionState previousInsertCommandConnectionState;
public void openInsertCommandConnection()
{
previousInsertCommandConnectionState = Adapter.InsertCommand.Connection.State;
if (((Adapter.InsertCommand.Connection.State & ConnectionState.Open) != ConnectionState.Open))
{
Adapter.InsertCommand.Connection.Open();
}
}
public void closeInsertCommandConnection()
{
if (previousInsertCommandConnectionState == ConnectionState.Closed)
{
Adapter.InsertCommand.Connection.Close();
}
}
public virtual int InsertCommand(byte[] value, long id1, long id2)
{
if ((value == null))
{
throw new ArgumentNullException("value");
}
else
{
Adapter.InsertCommand.Parameters[0].Value = value;
}
Adapter.InsertCommand.Parameters[1].Value = id1;
Adapter.InsertCommand.Parameters[2].Value = id2;
ConnectionState previousConnectionState = Adapter.InsertCommand.Connection.State;
if ((Adapter.InsertCommand.Connection.State & ConnectionState.Open) != ConnectionState.Open)
{
Adapter.InsertCommand.Connection.Open();
}
int returnValue = Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
令我惊讶的是,第二种方法比使用数据集中自动生成的插入语句慢大约1.5倍:
public virtual int Insert(byte[] value, long id1, long id2) {
if ((value == null)) {
throw new global::System.ArgumentNullException("value");
}
else {
this.Adapter.InsertCommand.Parameters[0].Value = ((byte[])(value));
}
this.Adapter.InsertCommand.Parameters[1].Value = ((long)(id1));
this.Adapter.InsertCommand.Parameters[2].Value = ((long)(id2));
global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State;
if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.InsertCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.InsertCommand.Connection.Close();
}
}
}
我真的不明白这是怎么回事,因为打开和关闭连接应该是最耗时的任务。
任何想法都是适用的。