2015-02-06 61 views
-2

與當前連接關聯的交易已完成但尚未處理。事務必須在連接可用於執行SQL語句之前進行處理。爲什麼突然出現Connection Dispose錯誤?

protected string installDatabase(string connectionString, bool createSampleData,string scriptpath) 
{ 
    //uncomment this line to support transactions 
    using (var scope = new System.Transactions.TransactionScope()) 
    { 
     string scriptsFolder = scriptpath + "\\install\\Scripts"; 
     string createDatabaseFile = string.Format(@"{0}\{1}", scriptsFolder, "Campus.sql"); 
     string error = proceedSQLScripts(createDatabaseFile, connectionString); 
     if (!String.IsNullOrEmpty(error)) 
     { 
      return error; 
     } 
     scope.Complete();  
    } 
    return "true"; 
}  

protected string proceedSQLScripts(string pathToScriptFile, string connectionString) 
{ 
    List<string> statements = new List<string>(); 
    SqlConnection conn = new SqlConnection(connectionString); 
    conn.Open(); 
    using (Stream stream = File.OpenRead(pathToScriptFile)) 
    using (StreamReader reader = new StreamReader(stream)) 
    { 
     string statement = string.Empty; 
     while ((statement = readNextStatementFromStream(reader)) != null) 
     { 
      statements.Add(statement); 
     } 
    } 
    try 
    { 
     foreach (string stmt in statements) 
     { 
      { 
       SqlCommand command = new SqlCommand(stmt, conn); 
       command.ExecuteNonQuery(); 
       //conn.Close(); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     return ex.Message; 
    } 
    finally 
    {  
     conn.Close(); 
    } 
    return string.Empty; 
} 
+1

請加上語言標記。 – Jens 2015-02-06 06:46:05

+0

*你有哪些錯誤? – 2015-02-06 08:09:13

+0

string error = proceedSQLScripts(createDatabaseFile,connectionString);在這裏我得到了這個錯誤! (與當前連接相關的事務已經完成但尚未處理,事務必須在連接可用於執行SQL語句之前進行處理。) – 2015-02-09 06:37:08

回答

0

試試下面的代碼

Finally 
    { 
     conn.Close(); 
     conn.Dispose(); 
    } 
+0

此答案不解釋如何解決問題。請嘗試多解釋一下,並且最好顯示將代碼插入到海報代碼中的位置。 – Claies 2015-02-06 08:35:11

+0

我假設它進入'finally'塊... – 2015-02-06 08:44:18

+0

是的,它進入finally塊,然後我在這裏得到了這個錯誤(字符串錯誤= proceedSQLScripts(createDatabaseFile,connectionString)) – 2015-02-09 06:40:03

相關問題