我有这段代码:
//open database connection on the server
con = new MySqlConnection("server=localhost;database=GPS;uid=root;pwd=****");
con.Open();
if (con.State == ConnectionState.Closed)
{
cmd = new MySqlCommand("insert into data values (null, ?Parname , ?Parname2, ?Parname3, ?Parname4, ?Parname5, ?Parname6, ?Parname7);", con);
cmd.Parameters.Add("?Parname", MySqlDbType.Double).Value = Math.Round(deciLat, 5);
cmd.Parameters.Add("?Parname2", MySqlDbType.Double).Value = Math.Round(deciLon, 5);
cmd.Parameters.Add("?Parname3", MySqlDbType.Timestamp).Value = DateTime.Now;
if (card_number != null)
{
cmd.Parameters.Add("?Parname4", MySqlDbType.VarChar).Value = card_number;
}
else
{
cmd.Parameters.Add("?Parname4", MySqlDbType.VarChar).Value = null;
}
cmd.Parameters.Add("?Parname5", MySqlDbType.VarChar).Value = ConfigSettings.ReadSetting("reg");
cmd.Parameters.Add("?Parname6", MySqlDbType.VarChar).Value = ConfigSettings.ReadSetting("ser");
cmd.Parameters.Add("?Parname7", MySqlDbType.Double).Value = ellipHeight;
cmd.ExecuteNonQuery();
lastDBUpdate = DateTime.Now;
}
else
{
// local mysql database
con = new MySqlConnection("server=localhost;database=temp_GPS;uid=root;pwd=******");
con.Open();
if (con.State == ConnectionState.Open)
{
cmd = new MySqlCommand("insert into temp_data values (null, ?Parname , ?Parname2, ?Parname3, ?Parname4, ?Parname5, ?Parname6, ?Parname7);", con);
cmd.Parameters.Add("?Parname", MySqlDbType.Double).Value = Math.Round(deciLat, 5);
cmd.Parameters.Add("?Parname2", MySqlDbType.Double).Value = Math.Round(deciLon, 5);
cmd.Parameters.Add("?Parname3", MySqlDbType.Timestamp).Value = DateTime.Now;
if (card_number != null)
{
cmd.Parameters.Add("?Parname4", MySqlDbType.VarChar).Value = card_number;
}
else
{
cmd.Parameters.Add("?Parname4", MySqlDbType.VarChar).Value = null;
}
cmd.Parameters.Add("?Parname5", MySqlDbType.VarChar).Value = ConfigSettings.ReadSetting("reg");
cmd.Parameters.Add("?Parname6", MySqlDbType.VarChar).Value = ConfigSettings.ReadSetting("ser");
cmd.Parameters.Add("?Parname7", MySqlDbType.Double).Value = ellipHeight;
cmd.ExecuteNonQuery();
lastDBUpdate = DateTime.Now;
}
}
我想让我的代码工作,如果例如连接状态正常并且已建立与服务器的连接然后将结果保存在服务器上,如果连接到服务器失败然后连接并保存到我的本地数据库,这将始终可以访问。
有人可以安排我的代码按我的意愿工作,因为我不知道如何实现它。
谢谢
答案 0 :(得分:1)
创建一个函数GetConnection()并使用此函数始终获得连接。
记下代码以检查连接状态并基于此返回连接。
public MySqlConnection GetConnection(MySqlConnection con)
{
if (con.State == ConnectionState.Closed)
{
// local mysql database
con = new MySqlConnection("server=localhost;database=temp_GPS;uid=root;pwd=******");
con.Open();
}
return con;
}