【问题标题】:Why are there connections open to my databases?为什么我的数据库打开了连接?
【发布时间】:2010-06-06 02:01:58
【问题描述】:

我有一个程序将用户项目存储为数据库。自然,程序应该允许用户根据需要创建和删除数据库。当程序启动时,它会在特定 SQLServer 实例中查找具有程序预期结构的所有数据库。然后将这些数据库加载到一个列表框中,以便用户可以选择一个作为项目打开。

当我尝试从程序中删除数据库时,我总是收到一条 SQL 错误,提示数据库当前处于打开状态并且操作失败。我已经确定检查要加载的数据库的代码导致了问题。不过我不确定为什么,因为我很确定所有连接都已正确关闭。

这里是所有相关的功能。调用 BuildProjectList 后,从 ExecuteSQL 运行“DROP DATABASE database_name”失败并显示消息:“无法删除数据库,因为它当前正在使用中”。我正在使用 SQLServer 2005。

private SqlConnection databaseConnection;
private string connectionString;
private ArrayList databases;

public ArrayList BuildProjectList()
{
    //databases is an ArrayList of all the databases in an instance
    if (databases.Count <= 0)
    {
      return null;
    }
    ArrayList databaseNames = new ArrayList();
    for (int i = 0; i < databases.Count; i++)
    {
      string db = databases[i].ToString();
      connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";";
      //Check if the database has the table required for the project
      string sql = "select * from TableExpectedToExist";
      if (ExecuteSQL(sql)) {
        databaseNames.Add(db);
      }
    }
    return databaseNames;
}

private bool ExecuteSQL(string sql)
{
    bool success = false;
    openConnection();
    SqlCommand cmd = new SqlCommand(sql, databaseConnection);
    try
    {
      cmd.ExecuteNonQuery();
      success = true;
    }
    catch (SqlException ae)
    {
      MessageBox.Show(ae.Message.ToString());
    }
    closeConnection();
    return success;
}

public void openConnection()
{
    databaseConnection = new SqlConnection(connectionString);
    try
    {
      databaseConnection.Open();
    }
    catch(Exception e)
    {
      MessageBox.Show(e.ToString(), "Error", 
      MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

public void closeConnection()
{
    if (databaseConnection != null)
    {
      try
      {
        databaseConnection.Close();
      }
      catch (Exception e)
      {
        MessageBox.Show(e.ToString(), "Error",
        MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
}

【问题讨论】:

    标签: c# sql sql-server-2005 database-connection


    【解决方案1】:

    SqlConnection 类轮询实际的数据库连接。如果关闭SqlConnection,连接将返回到连接池。要防止这种行为,请设置SqlConnection.Pooling = false;

    编辑

    约翰似乎在这里更重要。但您可能还必须牢记民意调查。

    【讨论】:

    • 我找不到 SQLConnection.Pooling 属性,但我尝试在删除数据库之前调用 SQLConnection.ClearAllPools() 并成功了。谢谢!
    【解决方案2】:

    两个厘米。首先,你应该使用 using 语句,这样你的可能会更干净。

    关于主题的更多信息,当您尝试删除数据库时,您正在连接到数据库!而是连接到主数据库。

    【讨论】:

    • 我不认为这是问题所在。我在删除它之前尝试连接到主数据库,但它没有解决任何问题。如果不调用 BuildProjectList,它会起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2022-07-07
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多