【发布时间】: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