0

我有这段代码用于将一个表复制到另一个表,但是在执行命令语句时出现错误。

错误表示连接未打开或无效。当我调试时,我可以看到它已打开。真不知道为什么无效。

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

如果这两个数据库位于不同的服务器上,这甚至可能吗?也许我需要同时打开两个连接或类似的东西?

4

2 回答 2

2

将连接对象传递给MySqlCommand构造函数:

cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data", con);
于 2012-05-28T17:09:40.230 回答
0
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();
                }
            }
        }
    }
}
于 2012-05-28T17:12:17.043 回答