2010-06-06 3 views
0

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

답변

2

SqlConnection 클래스는 실제 데이터베이스 연결을 폴링합니다. SqlConnection을 닫으면 연결이 연결 풀로 반환됩니다. 이 문제를 방지하려면 SqlConnection.Pooling = false;을 설정하십시오.

편집

요한은 여기서 점에 더 많은 것 같다. 그러나 폴링을 염두에 두어야 할 수도 있습니다.

+0

SQLConnection.Pooling 속성을 찾을 수 없지만 데이터베이스를 삭제하기 전에 SQLConnection.ClearAllPools()를 호출 해 보았습니다. 트릭을 수행했습니다. 감사! – Everett

2

두 개의 의견입니다. 첫째로, using 문을 사용해야하며 당신의 것이 더 깨끗할 것입니다.

주제에 대한 추가 정보를 삭제하면 데이터베이스에 연결 중입니다! 대신 master 데이터베이스에 연결하십시오.

+0

나는 문제가되지 않습니다. 삭제하기 전에 마스터 db에 연결을 시도했지만 아무 것도 수정하지 않았습니다. BuildProjectList를 호출하지 않으면 작동합니다. – Everett

관련 문제