Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SQL server connection

Tags:

c#

sql

HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not.

Thanks Andy

like image 539
andy Avatar asked Apr 18 '26 11:04

andy


2 Answers

Here's a little console app example that will cycle through a list of connections and attempt to connect to each, reporting success or failure. Ideally you'd perhaps want to extend this to read in a list of connection strings from a file, but this should hopefully get you started.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace SQLServerChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use a dictionary to associate a friendly name with each connection string.
            IDictionary<string, string> connectionStrings = new Dictionary<string, string>();

            connectionStrings.Add("Sales Database", "< connection string >");
            connectionStrings.Add("QA Database", "< connection string >");

            foreach (string databaseName in connectionStrings.Keys)
            {
                try
                {
                    string connectionString = connectionStrings[databaseName];

                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        connection.Open();
                        Console.WriteLine("Connected to {0}", databaseName);
                    }
                }
                catch (Exception ex)
                {
                    // Handle the connection failure.
                    Console.WriteLine("FAILED to connect to {0} - {1}", databaseName, ex.Message);
                }
            }

            // Wait for a keypress to stop the console closing.
            Console.WriteLine("Press any key to finish.");
            Console.ReadKey();
        }
    }
}
like image 134
Stuart Davies Avatar answered Apr 19 '26 23:04

Stuart Davies


Look at the SqlConnection Class. It includes a basic sample. Just put a loop around that sample to connect to each server, and if any server fails to connect it throws an exception.

Then just set it up as a scheduled task in Windows.

A nice way to report the status might be with an email, which can easily be sent out with SmtpClient.Send (the link has a nice simple sample.

like image 35
Hans Olsson Avatar answered Apr 19 '26 23:04

Hans Olsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!