连接状态已打开,但无效
本文关键字:无效 状态 连接 | 更新日期: 2023-09-27 18:35:43
我有这段代码,用于将一个表复制到另一个表,但是在执行命令语句时出错。
错误指出连接未打开或无效。当我调试时,我可以看到它已打开。真的不知道为什么是无效的。
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();
如果这两个数据库位于不同的服务器上,这甚至可能吗?也许我需要同时打开两个连接或类似的东西?
将连接对象传递给MySqlCommand
构造函数:
cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data", con);
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();
}
}
}
}
}