C# 如何在windows应用程序中使用singleton类进行数据库连接
在我的windows应用程序中,我使用Access数据库。当应用程序启动时,应该打开连接。我使用连接字符串调用过程/存储查询并访问数据。连接应一直打开,直到应用程序退出C# 如何在windows应用程序中使用singleton类进行数据库连接,c#,winforms,singleton,database-connection,global,C#,Winforms,Singleton,Database Connection,Global,在我的windows应用程序中,我使用Access数据库。当应用程序启动时,应该打开连接。我使用连接字符串调用过程/存储查询并访问数据。连接应一直打开,直到应用程序退出 我被要求使用singleton类。请帮助我如何使用singleton类进行数据库连接。要直接使用singleton,您必须从connection对象继承,这在OleDbConnection中是不可能的(因为它是密封的)。因此,您必须编写一个类,使用公开连接本身的公共属性,并使该包装类成为单例 但是,它的唯一目标是拥有一个连接实例
我被要求使用
singleton
类。请帮助我如何使用singleton类进行数据库连接。要直接使用singleton,您必须从connection对象继承,这在OleDbConnection中是不可能的(因为它是密封的)。因此,您必须编写一个类,使用公开连接本身的公共属性,并使该包装类成为单例
但是,它的唯一目标是拥有一个连接实例,您可以使用一个“Lazy”构造,它是线程安全的(因此,即使在单例中,我也会使用Lazy或LazyInitializer来准备线程)
同样,如果您合并了一个封装所有连接调用的类,那么对于单例来说,这将是一个完美的例子
*编辑**使用单个连接并重置的示例*
public static class Data
{
static OleDbConnection conn;
public static OleDbConnection Connection
{
get
{
if (conn == null)
LazyInitializer.EnsureInitialized(ref conn, CreateConnection);
return conn;
}
}
static OleDbConnection CreateConnection()
{
if (strDataFilePath == null)
throw new Exception("Datafile paths is not set");
//build connection, using strDataFilePath
var conn = new OleDbConnection("YourConnectionStringWithDataFilePath");
//other settings
//open
conn.Open();
return conn;
}
static string strDataFilePath;
public static string DataFilePath
{
get { return strDataFilePath; }
set
{
if(strDataFilePath==value)return;
strDataFilePath = value;
if(conn!=null){
conn.Close(); //NB, no checks were added if the connection is being used, but if the value is only set on startup or idle moments, this should be ok for the example.
conn.Dispose();
conn=null; //conn is reset, and (re)created the next time Connection is called
}
}
}
}
和初始化:
Data.DataFilePath = ".....";
使用连接:
var conn = Data.Connection; //Connection is created and opened on first call
我需要在连接字符串中有一个数据文件名,即在应用程序启动时,用户将选择数据文件,然后访问应用程序。在连接字符串中,我需要在运行时添加数据文件名。我声明了
公共字符串strDataFilePath代码>。我得到了“DataAccessLayer.Singleton01.strDataFilePath”:不能在静态类中声明实例成员。如果没有看到代码,我会说strDataFilePath前面必须有“static”关键字。如果您愿意,我可以添加一个示例,使用上面的连接实例,如果DataFilePath属性发生更改,该实例将被重置?是的,请添加一个示例。谢谢。我尝试了其他的例子,但你的答案是显而易见的,非常清楚。
Data.DataFilePath = ".....";
var conn = Data.Connection; //Connection is created and opened on first call