ConnectionState有六个属性值
ConnectionState.Broken;与数据源连接断开。只有在连接打开后才有可能发生这种情况。可以关闭处于这种状态下的连接,然后重新打开。
ConnectionState.Closed;连接处于关闭状态。
ConnectionState.Connecting;连接对象正在与数据源连接。
ConnectionState.Executing;连接对象正在执行命令。
ConnectionState.Fetching;连接对象正在检索数据。
ConnectionState.Open;连接处于打开状态
通常我们会常用到Open,Broken和Close去进行状态的判断。
例如:
一般建立连接的方式如下:
private static SqlConnection connection;
public static SqlConnection Connection
{
get
{
if (connection == null)
{
string connectionString = GetconnStr();
connection = new SqlConnection(connectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
return connection;
}
}
关闭连接:
public void Dispose()
{
if (connection.State == ConnectionState.Open || connection.State == ConnectionState.Broken)
connection.Close();
}
---------------------
作者:风林山火
来源:CSDN
原文:https://blog.csdn.net/zhaoleiwang/article/details/9851041
版权声明:本文为博主原创文章,转载请附上博文链接!