《C#與.NET 3.0進階程式設計》第22章讀書筆記

來源:互聯網
上載者:User
文章目錄
  • 第22章:使用 ADO.NET 訪問資料庫

第22章:使用 ADO.NET 訪問資料庫

以下的讀書筆記記了該章節 .NET 2.0 ADO.NET中新增的資料提供器原廠模式的內容。

22.7.2節:完整的資料提供器的例子

這一章節是用 Pubs,本人換用 SQL Server 2005 中樣本資料庫: AdventureWorks重寫程式碼:

app.config部分:

Code
<appSettings>
    <add key="provider" value="System.Data.SqlClient" />
    <add key="cnStr" value="Data Source=localhost;uid=sa;pwd=;Initial Catalog=AdventureWorks"/>
  </appSettings>

 

Main()方法部分:

Code
static void Main(string[] args)
    {
        //從config檔案中擷取連接字串和提供器
        string dp = ConfigurationManager.AppSettings["provider"];
        string cnStr = ConfigurationManager.AppSettings["cnStr"];
        //得到工廠提供器
        DbProviderFactory df = DbProviderFactories.GetFactory(dp);
        //得到連線物件
        DbConnection conn = df.CreateConnection();
        Console.WriteLine("Your connection object is a: {0}", conn.GetType().FullName);
        conn.ConnectionString = cnStr;
        conn.Open();
        //得到命令對象
        DbCommand cmd = df.CreateCommand();
        Console.WriteLine("Your command object is a: {0}", cmd.GetType().FullName);
        cmd.Connection = conn;
        cmd.CommandText = "Select * From Purchasing.Vendor";
        //從資料讀取器輸出資料
        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();
    }

 

程式使用微軟SQL Server 提供器來從 AdventureWorks 資料庫的 Purchasing.Vendor 表中讀取資料:

22.8節:<connentionStrings>元素

app.config檔案修改部分:

Code
<connectionStrings>
  <add name="SqlProviderAdventureWorks" connectionString="Data Source=localhost;uid=sa;pwd=;Initial Catalog=AdventureWorks" providerName="System.Data.SqlClient"/>
</connectionStrings>

 

Main()方法修改部分:

Code
string dp = ConfigurationManager.ConnectionStrings["SqlProviderAdventureWorks"].ProviderName;
string cnStr = ConfigurationManager.ConnectionStrings["SqlProviderAdventureWorks"].ConnectionString;

 

22.9節:安裝 Cars 資料庫

Cars.sql 指令檔在 SQL Server 2005 中運行時需要修改初始大小值。

注意粗體的部分:

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%)

作者在書中是按 SQL Server 2000 建立資料庫初始大小設定為2M的指令碼。

 

本書資源:

源碼下載頁連結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.