如果没有连接,如何忽略MySQL与数据库的连接

时间:2016-08-19 11:14:52

标签: c# mysql

我想在我的系统中保存并行数据库。我有两个目的地,数据库将被保存。首先在本地计算机(所以我使用localhost而不是IPaddress)和远程PC(我使用IP地址访问它)。 这是我的代码:

    static string MyConnectionString = "Server=localhost;Port=3306;Database=database freq logger;Uid=root;";
    static string MyConnectionString2 = "Server=192.168.41.105;Port=3306;Database=database freq logger;Uid=irfan;";
    MySqlConnection connection = new MySqlConnection(MyConnectionString);
    MySqlConnection connection2 = new MySqlConnection(MyConnectionString2);
    MySqlCommand cmd;

public void Read()
{
        while (port.IsOpen)
        {
            try
            {
                if (port.BytesToRead > 0)
                {
                    string message = port.ReadLine();
                    this.SetText(message);
                    connection.Open();
                    try
                    {
                        cmd = connection.CreateCommand();
                        cmd.CommandText = "INSERT INTO frequency(value)VALUES(@message)";
                        cmd.Parameters.AddWithValue("@message", message);
                        cmd.ExecuteNonQuery();
                    }

                    catch (Exception)
                    {
                        throw;
                    }
                    connection.Close();

                    if (connection2 != null && connection2.State == ConnectionState.Closed)
                    {
                        connection2.Open();
                        try
                        {
                            cmd = connection2.CreateCommand();
                            cmd.CommandText = "INSERT INTO frequency(value)VALUES(@message)";
                            cmd.Parameters.AddWithValue("@message", message);
                            cmd.ExecuteNonQuery();
                        }

                        catch (Exception)
                        {
                            throw;
                        }
                        connection2.Close();
                    }

                }
            }
            catch (TimeoutException) { }
        }
    }

所以我有2个connectionql(connection1和connection2) 我想忽略 connection2 ,但是连接没有连接。连接是以太网LAN。所以当我拔掉局域网时,我希望我的程序仍在运行  我总是在“connection2.Open();”中得到错误(当我在程序运行时突然拔掉以太网)。

我需要你的帮助,谢谢你

1 个答案:

答案 0 :(得分:0)

请勿尝试主动监控连接,只是捕获生成的异常并忽略它。您的问题是您的Connection2.Open()不在Try {} Catch {}块中,但在其外部。

试试这个

try
{
    connection2.Open();
    cmd = connection2.CreateCommand();
    cmd.CommandText = "INSERT INTO frequency(value)VALUES(@message)";
    cmd.Parameters.AddWithValue("@message", message);
    cmd.ExecuteNonQuery();
    connection2.Close();
}
catch
{
   // Do nothing - this should continue to work without being able to make the connection
}