Вопрос

Hello everyone i was hopping to get a little advice on how someone would go about doing something

  1. i need to test sql connection for a main server, if the connection returns false then i need to set a variable that will tell the program to use it own local sql ce database

how would yall go about testing that connection then setting that variable?

Would yall agree on something like this

try
{
  con.open();
  standalone=false;
  con.close();
}
catch
{
 standalone=true;
 con.close();
}
Это было полезно?

Решение

Not the best solution, but if you have a bunch of queries would be ok. Whenever you need to open a connection to your object you check if everything is ok with your first connection string. Otherwise your second conneciton string.

using (SqlConnection Conn = new SqlConnection(connectionString1))
{
    try
    {
        Conn.Open();
        // Here goes your statements for querying your db.

    }
    catch (Exception Ex)
    {
        using(SqlConnection Conn2 = new SqlConnection(connectionString2))
        {
            try
            {
                 Conn2.Open();
                 // Here goes your statements for querying your db.
            }
            catch(Exception Ex2)
            {
                 // Here goes your error handling code for the second connection
            }
        }
    }
}

Although the above might be a solution to your problem, I should state a concern, which have arisen since I read your question. Suppose you connect to your first database and you do any tranasction you need with it. After a little time there comes a problem and you cannot connect to your first db. So you will connect to your second db. Then the data of the second db will be incosistent with the data you had, when you were using the first db.

Другие советы

You need to handle sqlexception and if one occurs you can then use your local connection see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top