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();
}
啊 - 这很有道理。我改变了这一点,但不幸的是同样的错误:其他信息:连接必须是有效的并且打开。连接在这一点上是空的,这是写信息 – TMB87 2014-10-02 13:01:51
@Tom请看我的编辑。 – 2014-10-02 13:02:51
@你可以移动该行,并且可能应该将该行移到“MySqlConnection”构建的正下方。 – 2014-10-02 13:03:32