Create SQL Server Connection Objects in Code - ADO.NET

Q.  How will you create the SQL Server Connection Objects in Code? Choose the correct option.
- Published on 28 Jul 15

a. SqlConnection con = new SqlConnection ("Data Source=ServerName; Initial Catalog=DatabaseName;Integrated Security=True");
b. SqlConnection con = new SqlConnection();
 con.ConnectionString = ("Data Source=ServerName; Initial Catalog=DatabaseName;Integrated Security=True");
c. using (SqlConnection con = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName;Integrated Security=True"))
 {
 con.Open();
 - - - - - -
 - - - - - -
 }
d. All of the above codes are correct.

ANSWER: All of the above codes are correct.
 

    Discussion

  • Brijesh   -Posted on 19 Oct 15
    You can pass connection string in the constructor of SqlConnection or you can set connection string as property.
    If you are writing connection string with using block then there is no need to dispose connection object explicitly.
    using (SqlConnection con = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName;Integrated Security=True"))
    {
    con.Open();
    - - - - - -
    - - - - - -
    }
    Once the using block is over the CLR will immediately release the connection object by calling its Dispose() method. The Dispose() will automatically close the Connection before disposing it.

Post your comment / Share knowledge


Enter the code shown above:
 
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)