8.2.
1 Connection Object
Definition:
A Connection Object in .NET establishes and manages a session with a specific data source. It is
responsible for opening and closing the connection, setting the connection string, and
communicating with the data source.
A Connection object represents a unique session with a data source. In a client/server
database system, it may be equivalent to an actual network connection to the server.
Depending on the functionality the provider supports, some collections, methods, or
properties of a Connection object may not be available.
Key Features and Properties
Connection String:
Definition: A string that contains information required to establish the connection to the database,
such as server name, database name, user ID, and password.
Example:
State Property:
Definition: Indicates the current state of the connection (e.g., Closed, Open, Connecting,
Executing, Fetching, Broken).
Example:
Open() Method:
Definition: Opens a database connection with the settings specified in the connection string.
Example:
Close() Method:
Definition: Closes the connection to the database.
Example:
Dispose() Method:
Definition: Releases the connection object’s resources. Often used within a using statement for
automatic disposal.
Example:
ConnectionTimeout Property:
Definition: Specifies the time to wait while trying to establish a connection before terminating
the attempt and generating an error.
Example:
Types of Connection Objects
SqlConnection:
Connects to Microsoft SQL Server.
Example:
OleDbConnection:
Connects to various data sources using OLE DB.
Example:
OracleConnection:
Connects to Oracle databases.
Example:
OdbcConnection:
Connects to databases using ODBC drivers.
Example:
Best Practices
Use ‘using’ Statement: Ensures the connection is closed and resources are released automatically
even if an exception occurs.
Connection Pooling: Enhances performance by reusing active connections instead of creating
new ones for every request.
Automatic in ADO.NET: Connection pooling is enabled by default for .NET data
providers.
Exception Handling: Implement try-catch blocks to handle potential connection errors
gracefully.
Using Connection in C# Code