• +91 9723535972
  • info@interviewmaterial.com

Ado.net Interview Questions and Answers

Question - How to make SQL Server connection in ADO.NET?

Answer -

Consider the below example where a connection to the SQL Server has been established. An employee database will be used to connect. The C# code will be:

using (SqlConnection con = new SqlConnection(connectionString))    
{    
  con.Open();         
}
Using block will be useful in closing the connection automatically. It is not required to explicitly call the close() method, because using block will do this implicitly when the code exits the block.

// ConnectionExample.cs

using System;  
using System.Data.SqlClient;  
namespace ConsoleApplicationExample  
{  
    class ConnectionExample  
    {  
        static void Main(string[] args)  
        {  
            new Program().ConnectingMethod();  
        }  
        public void ConnectingMethod()  
        {  
            using (  
                     // Creating Connection  
                     SqlConnection conn = new SqlConnection("data source=.; database=employee; integrated security=SSPI")  
                 )  
            {  
                conn.Open();  
                Console.WriteLine("Connection Has Been Successfully Established.");  
            }  
        }  
    }  
}  
Output:

Connection Has Been Successfully Established.
Press any key to continue...
On execution, if the connection has been established, a message will be displayed on an output window.

If the connection is not created with the help of using a block, a connection must be closed explicitly.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners