Sqlconnection Signature
Sqlconnection Signature
Sqlconnection Signature
Connection does not close explicitly even it goes out of scope. Therefore,
you must explicitly close the connection by calling Close() method.
SqlConnection Signature
1. public sealed class SqlConnection : System.Data.Common.DbConnecti
on, ICloneable, IDisposable
SqlConnection Constructors
Constructors Description
SqlConnection Methods
Method Description
SqlConnection Example
Now, let's create an example that establishes a connection to the SQL
Server. We have created a Student database and will use it to connect.
Look at the following C# code.
1. using (SqlConnection connection = new SqlConnection(connectionStrin
g))
2. {
3. connection.Open();
4. }
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().Connecting();
10. }
11. public void Connecting()
12. {
13. using (
14. // Creating Connection
15. SqlConnection con = new SqlConnection("data source=
.; database=student; integrated security=SSPI")
16. )
17. {
18. con.Open();
19. Console.WriteLine("Connection Established Successfully");
20. }
21. }
22. }
23. }
Output:
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().Connecting();
10. }
11. public void Connecting()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=stude
nt; integrated security=SSPI");
18. con.Open();
19. Console.WriteLine("Connection Established Successfully");
20. }
21. catch (Exception e)
22. {
23. Console.WriteLine("OOPs, something went wrong.\n"+e);
24. }
25. finally
26. { // Closing the connection
27. con.Close();
28. }
29. }
30. }
31. }
Output: