gpt4 book ai didi

c# - mySQL通过c#写数据到数据库

转载 作者:行者123 更新时间:2023-11-29 05:20:46 25 4
gpt4 key购买 nike

我有以下代码,我基本上是从 mysql 中获取数据并在 SQL 服务器中插入数据。

SQL 服务器部分工作正常,但我不知道如何保持 mysql 连接打开以进行更新。当 mysql 在 foreach 循环中执行 reader 时,它会报错:

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();

}

最佳答案

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

更多information

关于c# - mySQL通过c#写数据到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com