我有以下代码,我基本上从SQL服务器中获取mysql和plonking的数据。
SQL Server部分工作正常,但我无法弄清楚如何保持mysql连接打开以进行更新。当它在foreach循环中执行mysql执行读取器时,它会出现错误:
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();
}
答案 0 :(得分:2)
MySqlConnection connection = new MySqlConnection(MyConString);
connection.open(); // insert this line
了解更多information
答案 1 :(得分:1)
它失败的原因是因为你不想在这里执行一个阅读器,你只想执行语句和,因为你没有初始化带连接的命令:
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
...
MySqlCommand SQLup = new MySqlCommand(mySQL, connection);
SQLup.ExecuteNonQuery();