我正在创建一个 C# 服务器,它打开一个命名管道并收集客户端发送给它的数据。基本上,我使用 .NET MySql 连接器和 MySqlConnection 类将收集到的信息存储在 mysql 数据库中。我还添加了一个回退规则,以防数据库无法访问,将客户端发送的信息缓冲在 SQL 文件中,并在再次可用时将其导入数据库。一切正常,除非数据库完全消失(例如,当运行数据库的服务器因为崩溃而不再在网络上时),Connect() 方法需要永远抛出异常。这是不可接受的,因为客户端发送了大量数据。有没有什么办法解决这一问题?如果查询因表不存在或类似原因而失败,它会立即返回错误。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using MySql.Data.MySqlClient;
namespace PipeServer
{
class MySqlConnector
{
//register logger
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public delegate void MessageReceivedHandler(string message);
public event MessageReceivedHandler MessageReceived;
private string host;
private string database;
private string user;
private string password;
private MySqlConnection connection;
private List<string> rows = new List<string>();
public MySqlConnector()
{
this.host = Settings.Default.db_host;
this.database = Settings.Default.db_schema;
this.user = Settings.Default.db_user;
this.password = Settings.Default.db_pw;
string myConnectionString = "SERVER=" + this.host + ";" +
"DATABASE=" + this.database + ";" +
"UID=" + this.user + ";" +
"PASSWORD=" + this.password + ";";
connection = new MySqlConnection(myConnectionString);
}
public bool Connect()
{
if (connection.State != System.Data.ConnectionState.Open)
{
try
{
connection.Open();
this.MessageReceived("Connected to Database");
return true;
}
catch (MySqlException ex)
{
log.Error("failed to connect! mysql error: " + ex);
this.MessageReceived("No Database connection - Error: "+ex);
return false;
}
}
else
{
this.MessageReceived("Connected to Database");
return true;
}
}
.
.
.
}
}
任何提示都非常感谢!提前致谢!