ADO .NET – Connection to SQL Server

Connection to SQL Server:

  • Instantiate SqlConnection by invoking parameterized constructor.
  • We need to invoke Open() method on SqlConnection object to establish connection
  • Handle the Exception in case of invalid input values given
  • Close the connection in finally block.
using System;
using System.Data.SqlClient;
namespace Practice
{
            class Program
            {
                        static void Main(string[] args)
                        {
                                    SqlConnection con = null;
                                    try
                                    {
                                                con = new SqlConnection(“data source=.; database=fullstack; integrated security=SSPI”);
                                                con.Open();
                                                Console.WriteLine(“Connected”);
                                    }
                                    catch (Exception e)
                                    {
                                                Console.WriteLine(“OOPs, something went wrong.” + e);
                                    }
                                    finally
                                    {
                                                con.Close();
                                                Console.WriteLine(“Connection closed”);
                                    }
                        }
            }
}
Scroll to Top