2012-05-28 146 views
0

我有用於將一個表複製到另一個表的代碼,但執行命令語句時出錯。連接狀態已打開但無效?

錯誤表示連接未打開或無效。當我調試時,我可以看到它被打開。 真的不知道爲什麼無效。

con.ConnectionString = ConfigurationManager.ConnectionStrings["Con2"].ConnectionString; 
con.Open(); 
cmd = new MySqlCommand("SELECT COUNT(*) FROM " + ConfigSettings.ReadSetting("main_base"), con); 
int nRows = Convert.ToInt32(cmd.ExecuteScalar()); 
con.Close(); 
if (nRows > 0) 
{ 
    con.ConnectionString = ConfigurationManager.ConnectionStrings["Con1"].ConnectionString; 
    con.Open(); 
    cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data"); 
    cmd.ExecuteScalar(); 
} 

一切順利,直到最後一個命令:

cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data"); 
cmd.ExecuteScalar(); 

這甚至可能如果這兩個數據庫在不同的服務器?也許我需要同時打開兩個連接或類似的東西?

回答

2

傳遞連接對象的MySqlCommand構造:

cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data", con); 
+1

OMG我沒有看到:)謝謝 –

0
using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["Con2"].ConnectionString)) 
{ 
    conn.Open(); 
    using (var cmd = conn.CreateCommand()) 
    { 
     cmd.CommandText ="SELECT COUNT(*) FROM " + ConfigSettings.ReadSetting("main_base"); 
     int nRows = Convert.ToInt32(cmd.ExecuteScalar()); 
     if (nRows > 0) 
     { 
      using (var conn2 = new MySqlConnection(ConfigurationManager.ConnectionStrings["Con1"].ConnectionString)) 
      { 
       conn2.Open(); 
       using (var cmd2 = conn2.CreateCommand()) 
       { 
        cmd2.CommandText ="INSERT INTO temp_data SELECT * FROM data"; 
        cmd2.ExecuteScalar(); 
       } 
      } 
     } 
    } 
} 
相關問題