What is Connection Object in ADO.NET?
In ADO.NET architecture connection object represents a connection to Data Source.
The connection object represents the physical connection to a Data Source.
The connection object contains all the information to establish the connection to Data Source.
Basic steps are:
- Create Database
- Create connection object
- Set the provider
- Specify the data source
Connection object have properties specify user credentials and location of the Data Source and name of it for the connection.
You can manage the connection by using the method of the connection object.
To acquire the functionality of ADO.NET architecture, you have to use System.Data namespace.
Connection object have ConnectionString property. Depends on the parameter specified in the Connection String, ADO.NET connection object connects to the specified database.
OLEDB DataProvider connection string required two parameters:
- Provider = Microsoft.Jet.OLEDB.4.0
- DataSource = DatabaseName
Create OLDE DB Connection object:
OleDbConnection con = new OleDbConnection();
ConnectionString Property:
- A ConnectionString property has group of attributes separated by semi-colon (;). This attributes are information that is required to connect with Data Source.
- Syntax for C#:
String ConString = “key1=value1;key2=value2;key3=value3;…..;”;
- ConnectionString is different for each .NET Data Provider.
- The attributes of the ConnectionString property depends on the DataProvider and Data Source you are using to connect with Data Source.
- Example for C#:
String ConString = “Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\ProjectDatabase\dbStudent.accdb”
- By default, ConnectionString property is an empty string.
Properties of OleDbConnection object:
| Property |
Data Type |
Description |
| ConnectionString |
String |
Controls the string used to connect with Data Source. |
| ConnectionTimeout |
Int |
Specifies the time, in seconds, that how long the connection object will try to connect with Data Source. (Read-only). |
| Database |
String |
Returns the name of the database you are, or will be, connected to. (Read-only). |
| DataSource |
String |
Returns the server name of the Data Source(Read-only). |
| Provider |
String |
Gets the name of the OLE DB provider specified in the “Provider=” clause of the ConnectionString. (Read-only). |
| ServerVersion |
String |
Returns the version of the server of your Data Source. (Read-only) |
| State |
ConnectionState |
Returns the current state of the connection. (Read-only) |
Methods of the OleDbConnection object:
- Open(): it opens the connection to our database.
- Close(): it closes the database connection.
- Dispose(): it releases the resources on the connection object.
- State(): returns 0 for not connected or 1 for connected. Returns state of connection object.