连接状态是否已打开但无效?

时间:2012-05-28 17:03:46

标签: c# mysql database connection

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

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

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

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

2 个答案:

答案 0 :(得分:2)

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

cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data", con);

答案 1 :(得分: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();
                }
            }
        }
    }
}