外部事件是否会导致打开的 DbConnection 关闭?

Can external events cause an open DbConnection to close?

我的情况是我正在创建一个 OleDbTransaction 稍后将被提交或回滚。由于相应的 OleDbConnection 需要在事务的生命周期内保持打开状态,我想知道是否某些外部事件(例如 SQL 服务器崩溃或我的网络连接断开)会导致连接关闭?我知道我可以侦听 DbConnection.StateChange 事件,但如果唯一可以更改连接状态的代码是我自己的,那么我就不需要为此大惊小怪了。谢谢。

编辑:

这里有一些代码可以为问题添加额外的上下文:

public class DBAccess {
    private OleDbConnection cn = null;
    private OleDbTransaction tn = null;
    private const string cnString = "my connection string";

    public void UpdateField(string fieldName, object data, int key) {
        if (tn == null) {
            cn = new OleDbConnection(cnString);
            cn.StateChange += Connection_StateChange;
            tn = cn.BeginTransaction();
        }

        OleDbCommand cmd = new OleDbCommand("UPDATE MYTABLE SET " + fieldname + "=" + data.ToString() + "WHERE TABLEKEY=" + key, cn, tn);

        if (cmd.ExecuteNonQuery() != 1) {
            throw new ApplicationException();
        }
    }

    public void Commit() {
        if (tn != null) {
            tn.Commit();
            cn.Close();
            tn = null;
        }
    }

    public void Rollback() {
        if (tn != null) {
            tn.Rollback();
            cn.Close();
            tn = null;
        }
    }

    private void Connection_StateChange(object sender, StateChangeEventArgs e) {
        // can anything other than my code calling cn.Close() get me here?
}

在我的应用程序中,用户可能会在一段时间内对 table 中的不同字段进行多次更改...每个更改都是对 UpdateField() 的单独调用。当他们准备好保存他们的更改时,他们会按下保存按钮,代码会调用我的 class 的 Commit() 方法......还会有一个放弃更改按钮,这会导致调用我的 class 的 Rollback() 方法。因此,连接和事务需要在一段时间内保持打开状态。在此期间,与数据库的连接可能会发生某些事情,导致提交或回滚失败。如果注册 StateChange 事件意味着我会立即收到数据库现在无法访问的通知,那么我可以做一些事情。否则我必须在 commit/rollback 时间处理它。再次感谢。

希望我没有正确理解您的问题。通常您打开连接,提交事务,然后检查是否有任何行受到影响。如果返回 0 行,那么您就知道没有行被提交,您可以再试一次,或者...此外,如果您将整个内容包装在 "try > catch" 中,那么您可以进一步捕获错误。

如果您打开一个连接然后连接关闭(由于某些外部原因)然后您尝试提交该命令,将抛出一个错误,您可以在 catch 中捕获该错误。

"try > catch" 将捕获发生的错误,"int result..." 将显示您的更改是否已提交。

https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.executenonquery(v=vs.110).aspx

类似于:

try 
{
    //....
    int result = myOleDBCommand.ExecuteNonQuery();
    if (result <= 0) { /*the command executed but, nothing changed on the datasource so you can decide what to do here*/ }
}
catch (Exception ex) 
{
    //if you get here then a problem has occurred and you can choose how to deal with it.
}