我似乎有两个选择:
- 让我的班级实现
IDisposable
。将我的DbCommand
实例创建为private readonly
字段,并在构造函数中添加它们使用的参数。每当我想写入数据库时,绑定到这些参数(重用相同的命令实例),设置Connection
andTransaction
属性,然后调用ExecuteNonQuery
. 在该Dispose
方法中,调用Dispose
这些字段中的每一个。 - 每次我想写入数据库时,写
using(var cmd = new DbCommand("...", connection, transaction))
一下命令的用法,并在每次调用之前添加参数并绑定到它们ExecuteNonQuery
。我假设我不需要每个查询的新命令,每次打开数据库时都需要一个新命令(对吗?)。
这两者似乎都有些不雅,而且可能不正确。
对于#1,我的用户很烦我这个类现在IDisposable
只是因为我使用了几个DbCommand
s (这应该是他们不关心的实现细节)。我也有点怀疑保留一个DbCommand
实例可能会无意中锁定数据库或其他什么?
对于#2,每次我想写入数据库时,感觉就像我在做很多工作(就 .NET 对象而言),尤其是在添加参数时。似乎我每次都创建相同的对象,这感觉像是不好的做法。
作为参考,这是我当前的代码,使用#1:
using System;
using System.Net;
using System.Data.SQLite;
public class Class1 : IDisposable
{
private readonly SQLiteCommand updateCookie = new SQLiteCommand("UPDATE moz_cookies SET value = @value, expiry = @expiry, isSecure = @isSecure, isHttpOnly = @isHttpOnly WHERE name = @name AND host = @host AND path = @path");
public Class1()
{
this.updateCookie.Parameters.AddRange(new[]
{
new SQLiteParameter("@name"),
new SQLiteParameter("@value"),
new SQLiteParameter("@host"),
new SQLiteParameter("@path"),
new SQLiteParameter("@expiry"),
new SQLiteParameter("@isSecure"),
new SQLiteParameter("@isHttpOnly")
});
}
private static void BindDbCommandToMozillaCookie(DbCommand command, Cookie cookie)
{
long expiresSeconds = (long)cookie.Expires.TotalSeconds;
command.Parameters["@name"].Value = cookie.Name;
command.Parameters["@value"].Value = cookie.Value;
command.Parameters["@host"].Value = cookie.Domain;
command.Parameters["@path"].Value = cookie.Path;
command.Parameters["@expiry"].Value = expiresSeconds;
command.Parameters["@isSecure"].Value = cookie.Secure;
command.Parameters["@isHttpOnly"].Value = cookie.HttpOnly;
}
public void WriteCurrentCookiesToMozillaBasedBrowserSqlite(string databaseFilename)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + databaseFilename))
{
connection.Open();
using (SQLiteTransaction transaction = connection.BeginTransaction())
{
this.updateCookie.Connection = connection;
this.updateCookie.Transaction = transaction;
foreach (Cookie cookie in SomeOtherClass.GetCookieArray())
{
Class1.BindDbCommandToMozillaCookie(this.updateCookie, cookie);
this.updateCookie.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
#region IDisposable implementation
protected virtual void Dispose(bool disposing)
{
if (!this.disposed && disposing)
{
this.updateCookie.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
~Class1()
{
this.Dispose(false);
}
private bool disposed;
#endregion
}