无废话ADO.NET 第二章 关于连接

以SQLServer为例子进行说明,包含以下内容:

  如何进行连接

  如何关闭连接

  池的问题

  连接状态

1.如何进行连接

// 创建连接实例
DbConnection myConnection = new SqlConnection();
// 设置连接字符串
myConnection.ConnectionString = "user id=userName;password=pass;initial catalog=northwind;data source=mySQLServer;Connect Timeout=30";
// 打开连接
myConnection.Open();

2.如何关闭连接

// 创建连接实例
DbConnection myConnection = new SqlConnection();
// 设置连接字符串
myConnection.ConnectionString = "user id=userName;password=pass;initial catalog=northwind;data source=mySQLServer;Connect Timeout=30";
// 打开连接
myConnection.Open();
// 关闭连接,用Dispose也可以实现关闭;连接实例被垃圾回收器回收的时候不会自动释放数据库连接
myConnection.Close();

3.池的问题

  当连接打开时,将根据一种精确的匹配算法来创建连接池,该算法会使连接池与连接中的字符串相关联。
  每个连接池都与一个不同的连接字符串相关联。当新连接打开时,如果连接字符串不精确匹配现有池,则将创建一个新池。

  在以下示例中,将创建三个新的 SqlConnection 对象,但只需要使用两个连接池来管理这些对象。
  请注意,第一个和第二个连接字符串的差异在于为 Initial Catalog 分配的值

SqlConnection conn = new SqlConnection();
conn.ConnectionString
= "Integrated Security=SSPI;Initial Catalog=northwind";
conn.Open();
// Pool A is created.

SqlConnection conn
= new SqlConnection();
conn.ConnectionString
= "Integrated Security=SSPI;Initial Catalog=pubs";
conn.Open();
// Pool B is created because the connection Strings differ.

SqlConnection conn
= new SqlConnection();
conn.ConnectionString
= "Integrated Security=SSPI;Initial Catalog=northwind";
conn.Open();
// The connection String matches pool A.

 

  以上是连接字符串中与池相关的设置。

  关于池的概念这里不多说

4.连接状态

  通过连接实例的State属性,可以观察数据库连接的状态,共有如下种状态

            System.Data.ConnectionState.Closed
            System.Data.ConnectionState.Open
            System.Data.ConnectionState.Connecting
            System.Data.ConnectionState.Executing
            System.Data.ConnectionState.Fetching
            System.Data.ConnectionState.Broken

  StateChange事件在 Connection 的状态出现更改时发生。StateChange 事件接收 StateChangeEventArgs,它们使您能够使用 OriginalState 和 CurrentState 属性来确定 Connection 状态中的更改。OriginalState 属性它指示 Connection 在更改前的状态。CurrentState 它指示 Connection 在更改后的状态。

      myConnection.StateChange += new StateChangeEventHandler(OnStateChange);

protected static void OnStateChange(object sender, StateChangeEventArgs args)
{
Console.WriteLine(
"The current Connection state has changed from {0} to {1}.",
args.OriginalState, args.CurrentState);
}

原文地址:https://www.cnblogs.com/hutou/p/1963691.html