C# SqlConnection

Introduction

The SqlConnection class represents a connection with the SQL Server database. This class cannot be inherited.

Adding Namespaces

To use SqlConnection you need to add the following namespaces.

using System.Data.SqlClient;
Creating An Object
SqlConnection con = new SqlConnection();

Constructors

SqlConnection()

Initializes a new instance of the SqlConnection class.

SqlConnection con = new SqlConnection();
SqlConnection(string)

SqlConnection(string) initializes a new instance of the SqlConnection class when given a string that contains the connection string.

string cs = "data source=.;database=databaseName;integrated security=SSPI;";
SqlConnection con = new SqlConnection(cs);

Properties

ConnectionString

ConnectionString of the SqlConnection class when given a string that contains the connection string.

con.ConnectionString = "data source=.;database=databaseName;integrated security=SSPI;";
ConnectionTimeout

Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.

con.ConnectionString = "data source=.;database=databaseName;integrated security=SSPI;";
Database

After the connection is opened, return the name of the existing database to Database Properties.

string dbname = con.Database;
DataSource

DataSource return the current data source of SqlConnection class.

string dataSource = con.DataSource;
ServerVersion

Gets a string that contains the version of the instance of SQL Server to which the client is connected.

string version = con.ServerVersion;
WorkstationId

Gets a string that indentifies the database client.

if (ConnectionState.Open == con.State)

Functions

ChangeDatabase(string)

Changes the database name.

string Change = "Test";
con.ChangeDatabase(Change);
Close()

This Close () function is used to close the connection of Sql server but it is only possible when a connection is open.

con.Close();
Dispose()

Releases all resources that are used by the SqlConnection class.

con.Dispose();
Open()

Opens the database connection.

con.Open();

Write a comment


Name Email Message