如果没有连接,如何忽略MySQL连接到数据库
本文关键字:连接 数据库 MySQL 如果没有 何忽略 | 更新日期: 2023-09-27 18:03:02
我想在我的系统中进行并行数据库保存。我有两个保存数据库的目的地。首先在本地计算机(所以我使用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) { }
}
}
所以我有两个connectionsql (connection1和connection2)。
我想忽略connection2,尽管连接没有连接。连接方式为以太局域网。所以当我拔掉局域网时,我希望我的程序还在运行。我总是在"connection2.Open();"中得到错误(当我在程序运行时突然拔掉以太网时)。
我需要你的帮助,谢谢你
不要尝试主动监视连接,只需捕获产生的Exception并忽略它。你的问题是你的Connection2.Open()不在Try{} Catch{}块内,而是在它外面。
Try this
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
}