Document directory
- Chapter 2: using ADO. Net to access a database
Chapter 2: using ADO. Net to access a database
The following Reading Notes show the new data provider factory mode in. NET 2.0 ADO. net.
Section 22.7.2: complete data provider example
This section uses pubs to replace the sample database in SQL Server 2005: adventureworks to rewrite the program code:
App. config:
Code
<Deleetask>
<Add key = "provider" value = "system. Data. sqlclient"/>
<Add key = "cnstr" value = "Data Source = localhost; uid = sa; Pwd =; initial catalog = adventureworks"/>
</Appsettings>
Main () method:
Code
Static void main (string [] ARGs)
{
// Obtain the connection string and the provider from the config file
String dp = configurationmanager. receivettings ["provider"];
String cnstr = configurationmanager. receivettings ["cnstr"];
// Get the factory provisioner
Dbproviderfactory df = dbproviderfactories. getfactory (DP );
// Obtain the connection object
Dbconnection conn = DF. createconnection ();
Console. writeline ("your connection object is a: {0}", conn. GetType (). fullname );
Conn. connectionstring = cnstr;
Conn. open ();
// Obtain the command object
Dbcommand cmd = DF. createcommand ();
Console. writeline ("your command object is a: {0}", cmd. GetType (). fullname );
Cmd. Connection = conn;
Cmd. commandtext = "select * from purchasing. Vendor ";
// Output data from the data reader
Dbdatareader DR = cmd. executereader (commandbehavior. closeconnection );
Console. writeline ("your data reader object is a: {0}", dr. GetType (). fullname );
Console. writeline ("\ n ***** purchasing. vendor in adventureworks ");
While (dr. Read ())
Console. writeline ("-> {0}", Dr ["name"]);
Dr. Close ();
}
The program uses the Microsoft SQL Server Provider to read data from the purchasing. Vendor TABLE OF THE adventureworks database:
Section 22.8: <connentionstrings> element
Modify the app. config file:
Code
<Connectionstrings>
<Add name = "sqlprovideradventureworks" connectionstring = "Data Source = localhost; uid = sa; Pwd =; initial catalog = adventureworks" providername = "system. Data. sqlclient"/>
</Connectionstrings>
Modify the main () method:
Code
String dp = configurationmanager. connectionstrings ["sqlprovideradventureworks"]. providername;
String cnstr = configurationmanager. connectionstrings ["sqlprovideradventureworks"]. connectionstring;
Section 22.9: Install the cars Database
When running the cars. SQL script file in SQL Server 2005, you must modify the initial size value.
Note:
Code
Create Database [Cars] On (name = n' cars _ data', filename = n' c: \ Program Files \ Microsoft SQL Server \ MSSQL \ data \ cars_data.mdf ',
Size
=
3, Filegrowth = 10%)
In the book, the author creates a script with the initial size set to 2 MB based on SQL Server 2000.
Book resources:
Source code Download Page