检查 SQL 连接是打开还是关闭

如何检查它是否打开或关闭,我正在使用

 if (SQLOperator.SQLCONNECTION.State.Equals("Open"))

然而,即使国家是“开放的”,它也不能通过这一检查。

345279 次浏览

您应该使用 SqlConnection 状态

例如:

using System.Data;


if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
// do something
// ...
}

我使用以下方式 sqlconnection.state

if(conexion.state != connectionState.open())
conexion.open();

你也可以用这个

if (SQLCON.State == ConnectionState.Closed)
{
SQLCON.Open();
}

检查 MySQL 连接是否打开

ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
return true;
}
else
{
connection.Open();
return true;
}

以下是我正在使用的方法:

if (mySQLConnection.State != ConnectionState.Open)
{
mySQLConnection.Close();
mySQLConnection.Open();
}

我之所以没有简单地使用:

if (mySQLConnection.State == ConnectionState.Closed)
{
mySQLConnection.Open();
}

是因为 ConnectionState 还可以是:

Broken, Connnecting, Executing, Fetching

除了

Open, Closed

此外,Microsoft 声明关闭,然后重新打开连接“将刷新 State 的值” See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx

要检查数据库连接状态,只需执行以下操作

if(con.State == ConnectionState.Open){}

NET 文档说: State 属性: ConnectionState 值的按位组合

所以我觉得你应该去看看

!myConnection.State.HasFlag(ConnectionState.Open)

而不是

myConnection.State != ConnectionState.Open

因为 State 可以有多个标志。

在打开连接、检查状态之前,这段代码更具有防御性。 如果连接状态是中断的,那么我们应该尝试关闭它。中断意味着以前打开了连接,但没有正常工作。 第二个条件确定在尝试再次打开连接之前必须关闭连接状态,以便可以重复调用代码。

// Defensive database opening logic.


if (_databaseConnection.State == ConnectionState.Broken) {
_databaseConnection.Close();
}


if (_databaseConnection.State == ConnectionState.Closed) {
_databaseConnection.Open();
}

要检查 OleDbConnection 状态,请使用以下命令:

if (oconn.State == ConnectionState.Open)
{
oconn.Close();
}

返回 ConnectionState

public override ConnectionState State { get; }

这是另一个 ConnectionState枚举

public enum ConnectionState
{
//
// Summary:
//     The connection is closed.
Closed = 0,
//
// Summary:
//     The connection is open.
Open = 1,
//
// Summary:
//     The connection object is connecting to the data source. (This value is reserved
//     for future versions of the product.)
Connecting = 2,
//
// Summary:
//     The connection object is executing a command. (This value is reserved for future
//     versions of the product.)
Executing = 4,
//
// Summary:
//     The connection object is retrieving data. (This value is reserved for future
//     versions of the product.)
Fetching = 8,
//
// Summary:
//     The connection to the data source is broken. This can occur only after the connection
//     has been opened. A connection in this state may be closed and then re-opened.
//     (This value is reserved for future versions of the product.)
Broken = 16
}