2014-10-02 45 views
1

我已經得到了以下代碼,我基本上從mysql中獲取數據並在SQL Server中進行遷移。mySQL通過c#將數據寫入數據庫

SQL服務器部分工作正常,但我不能解決如何保持打開mysql連接來執行更新。當它MySQL的在foreach循環中執行的讀者也棄暗投明與錯誤:

An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll 

Additional information: Connection must be valid and open. 

代碼:

DB db = new DB(); 
      String sConfig_hostname = 
      String sConfig_dbname = 
      String sConfig_dbusername = 
      String sConfig_dbpassword = 
      string MyConString = "SERVER=" + sConfig_hostname + ";" + 
       "DATABASE=" + sConfig_dbname + ";" + 
       "UID=" + sConfig_dbusername + ";" + 
       "PASSWORD=" + sConfig_dbpassword + ";Allow Zero Datetime=true;"; 
      MySqlConnection connection = new MySqlConnection(MyConString); 
      string sQuery="Select * from inbox where Transferred = 0"; 

      MySqlDataAdapter myDA = new MySqlDataAdapter(sQuery, connection); 
      MySqlCommandBuilder cmb=new MySqlCommandBuilder(myDA); 

      DataTable MyDT = new DataTable(); 
      myDA.Fill(MyDT); 

      foreach (DataRow row in MyDT.Rows) 
      { 
       String SQL = String.Format("Insert into Inbox (Message, Received, Sender) VALUES ('{0}', '{1}', '{2}')", GeneralFunctions.SQLescape(row["TextDecoded"].ToString()), row["ReceivingDateTime"].ToString(), row["SenderNumber"].ToString()); 
       String mySQL = "Update inbox set Transferred = 1 where ID = " + row["ID"].ToString(); 
       db.Update(SQL); 

       MySqlCommand SQLup = new MySqlCommand(mySQL); 
       MySqlDataReader reader = SQLup.ExecuteReader(); 

      } 

回答

1

它的失敗的原因是因爲你不想在本地執行的讀者,你只是想執行的語句,因爲你不連接初始化命令:

MySqlConnection connection = new MySqlConnection(MyConString); 
connection.Open(); 

... 

MySqlCommand SQLup = new MySqlCommand(mySQL, connection); 
SQLup.ExecuteNonQuery(); 
+0

啊 - 這很有道理。我改變了這一點,但不幸的是同樣的錯誤:其他信息:連接必須是有效的並且打開。連接在這一點上是空的,這是寫信息 – TMB87 2014-10-02 13:01:51

+0

@Tom請看我的編輯。 – 2014-10-02 13:02:51

+0

@你可以移動該行,並且可能應該將該行移到「MySqlConnection」構建的正下方。 – 2014-10-02 13:03:32

2
MySqlConnection connection = new MySqlConnection(MyConString); 
connection.open(); // insert this line 

更多information