我正在创建一个C#服务器,它打开一个命名管道并收集客户端发送给它的数据。基本上,我使用.NET MySql Connector和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;
}
}
.
.
.
}
}
任何提示都非常感谢!提前致谢!
答案 0 :(得分:3)