我有一个程序将用户项目存储为数据库。当然,程序应该允许用户根据需要创建和删除数据库。当程序启动时,它会查找特定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);
}
}
}
我找不到SQLConnection.Pooling属性,但我在删除数据库之前尝试调用SQLConnection.ClearAllPools(),并且执行了该操作。谢谢! – Everett 2010-06-06 02:23:43