사용자 프로젝트를 데이터베이스로 저장하는 프로그램이 있습니다. 물론, 프로그램은 사용자가 필요에 따라 데이터베이스를 작성하고 삭제할 수 있도록해야합니다. 프로그램이 부팅되면 프로그램이 예상하는 구조를 가진 특정 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