作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
class SQLiteDatabase
{
String dbConnection;
static SQLiteConnection cnn;
static int connections = 0;
/// <summary>
/// Default Constructor for SQLiteDatabase Class.
/// </summary>
public SQLiteDatabase()
{
dbConnection = "Data Source=SQLiteOphthaMetrics.db;foreign keys=true;";
if (connections == 0)
{
cnn = new SQLiteConnection(dbConnection);
cnn.Open();
this.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS patients ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, birthday TEXT, gender TEXT, iriscolor INTEGER);");
this.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS images ( nameRed TEXT NOT NULL PRIMARY KEY, checksumRed TEXT NOT NULL, "
+ "nameGreen TEXT NOT NULL, checksumGreen TEXT NOT NULL, state INTEGER, cvalue REAL, sharpness REAL, deviation REAL, area REAL, redExposure REAL, "
+ "redGain REAL, greenExposure REAL, greenGain REAL, zfocus INTEGER, flipped INTEGER, patientID INTEGER, FOREIGN KEY (patientID) REFERENCES patients(id));");
}
connections++;
}
~SQLiteDatabase()
{
connections--;
if (connections == 0)
{
cnn.Close();
cnn.Dispose();
}
}
}
此代码抛出 DisposedObjectException
System.ObjectDisposedException was unhandled
Message=Auf das verworfene Objekt kann nicht zugegriffen werden.
Objektname: "SQLiteConnection".
Source=System.Data.SQLite
ObjectName=SQLiteConnection
StackTrace:
bei System.Data.SQLite.SQLiteConnection.CheckDisposed()
bei System.Data.SQLite.SQLiteConnection.Close()
bei EyeScanner.SQLiteDatabase.Finalize()
InnerException:
我目前只在代码中调用 SQLiteDatabase 一次,因此在析构函数中调用 connections = 1,但我不明白为什么它会在类析构函数完成之前处理该对象。
最佳答案
我相信您正在尝试在类实例准备好处理后处理连接。如果您对 SQLiteConnection 使用 using
语句会更好。 SQLiteConnection 类实现了 IDisposable,您将能够执行以下操作:
using(cnn = new SQLiteConnection(dbConnection))
{
cnn.Open();
this.ExecuteNonQuery("...your query");
}
这将作为一个try/finally
block ,即使发生异常,连接也会在using
block 之后关闭并释放。
对于数据库连接,最好的做法是尽量晚开,尽量早关。
关于c# - SQLiteConnection DisposedObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12951457/
class SQLiteDatabase { String dbConnection; static SQLiteConnection cnn;
这个问题的旧版本太长了,所以在多次尝试解决这个问题之后,我发现所有的问题都可以简化为一个简单的问题。为什么这会产生 SystemObjectDispose。 private async voi
我是一名优秀的程序员,十分优秀!