Javatpoint Logo
Javatpoint Logo

ADO.NET SqlConnection Class

It is used to establish an open connection to the SQL Server database. It is a sealed class so that cannot be inherited. SqlConnection class uses SqlDataAdapter and SqlCommand classes together to increase performance when connecting to a Microsoft SQL Server database.

Connection does not close explicitly even it goes out of scope. Therefore, you must explicitly close the connection by calling Close() method.

SqlConnection Signature

SqlConnection Constructors

Constructors Description
SqlConnection() It is used to initializes a new instance of the SqlConnection class.
SqlConnection(String)0 It is used to initialize a new instance of the SqlConnection class and takes connection string as an argument.
SqlConnection(String, SqlCredential) It is used to initialize a new instance of the SqlConnection class that takes two parameters. First is connection string and second is sql credentials.

SqlConnection Methods

Method Description
BeginTransaction() It is used to start a database transaction.
ChangeDatabase(String) It is used to change the current database for an open SqlConnection.
ChangePassword(String, String) It changes the SQL Server password for the user indicated in the connection string.
Close() It is used to close the connection to the database.
CreateCommand() It enlists in the specified transaction as a distributed transaction.
GetSchema() It returns schema information for the data source of this SqlConnection.
Open() It is used to open a database connection.
ResetStatistics() It resets all values if statistics gathering is enabled.

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.

Using block is used to close the connection automatically. We don't need to call close () method explicitly, using block do this for ours implicitly when the code exits the block.

// Program.cs


ADO Net SqlConnection Class 1

What, if we don't use using block.

If we don't use using block to create connection, we have to close connection explicitly. In the following example, we are using try-block instead of using block.

// Program.cs


ADO Net Sqlconnection Class 2
Next TopicADO.NET Command

Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials

B.Tech / MCA