我想在我的系统中进行并行数据库保存。我有两个数据库将被保存的目的地。首先在本地计算机(所以我使用 localhost 而不是 IP 地址)和远程 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个connectionsql(connection1和connection2)。
尽管连接未连接,但我想忽略 connection2 。连接是以太网 LAN。因此,当我拔掉 LAN 时,我希望我的程序仍在运行。
我总是在“connection2.Open();”中收到错误(当程序运行时突然拔掉以太网时)。
我需要你的帮助,谢谢
最佳答案
不要尝试主动监视连接,只需捕获产生的异常并忽略它即可。您的问题是您的 Connection2.Open() 不在 Try{} Catch{} block 内,而是在其外部。
试试这个
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
}
关于c# - 如果没有连接,如何忽略 MySQL 与数据库的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037674/