1. Using Assembly Oracle.ManagedDataAccess.dll
Using Oracle.ManagedDataAccess.Client;
Using System.Configuration;
Namespace ClassLibrary1
{
///
Database connection Practice single-instance mode
///
public class Oracledbconect
{
private static oracleconnection con = null;
private static Object obj = new Object ();
///
Define public static property instance, external call
///
public static OracleConnection Instance
{
Get
{
When the first thread runs here, the locker object is "locked" at this point,
When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked
After the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"
Double locking requires just one sentence.
if (con==null)
{
Lock (obj)
{
if (con==null)
{
var str = configurationmanager.connectionstrings["Dbcontection"]. connectionstring;//getting the database connection string in the configuration file
con = new OracleConnection (str);//instantiation
Try
{
Con. Open ();
}
catch (Exception e)
{
return null;
}
}
}
}
return con;
}
}
// 私有构造函数是一种特殊的实例构造函数。它通常用在只包含静态成员的类中。 // 如果类具有一个或多个私有构造函数而没有公共构造函数,则其他类(除嵌套类外)无法创建该类的实例。 //声明空构造函数可阻止自动生成默认构造函数,因为当编译器看到我们的类中没有定义构造函数时,编译器会帮我们生成一个公有的无参构造函数。 //注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。 // 但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。 private oracledbconect() { }}
}
C # uses singleton mode for database connectivity