gpt4 book ai didi

c# - SQLiteConnection DisposedObject

转载 作者:行者123 更新时间:2023-11-30 14:35:05 25 4
gpt4 key购买 nike

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/

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