1. 程式人生 > >C#---ADO.net

C#---ADO.net

Ado.net實際上就是一個用於訪問資料的類組,包括所有的System.data名稱空間以及巢狀的名稱空間,還有System.Xml名稱空間中的一些與資料訪問相關的專用庫,其位於System.data.dll程式集和相關的System.data.xxx.dll程式集中。

提供者物件:
1.連線物件:提供到資料來源的基本連線。
2.命令物件:用次物件向資料來源發出命令,對不同的提供者,該物件的名稱也不同,如Sqlcommand,OdbcCommand,OledbCommand.
3.CommandBuilder物件:用於構建SQL命令。
4.DataReader物件:讀取資料。
5.DataAdapter物件:可以執行對資料來源的各種操作。

使用者物件:
1.DataSet物件:一般表示一組相關表,包括Datatable和DataRelation物件
2.DataTable物件:代表DataSet中的一個表,包括DataColumn和DataRow物件。
3.DataRelation物件:代表有公共列的兩個表之間的關係

微軟的資料訪問簡史:
每個資料庫系統都有自己的函式組,用於訪問資料
ODBC的開發
OLE DB的開發
舊式的ActiveX Data Object是(ADO)
ADO.net在.net Framework 1.0中引入,隨其發展
ADO.net for Entities是面向專家級的高階介面

1、用DataReader讀取資料

//連線資料來源,包括SQL server,Oracle,ole db,odbc,其它內建的資料提供者
SqlConnection thisConnection = new SqlConnection(
//代表正在訪問的SQL Server名稱,格式為“計算機名\例項名”。
//句點表示當前伺服器例項,也可用名稱或計算機你的網路名稱代替它。
@”Data Source=.\SQLEXPRESS;”
[email protected]”AttachDbFilename=’C:\SQL Server 2000 Sample Databases\NORTHWND.MDF’;”
+ @”Integrated Security=True;Connect Timeout=30;User Instance=true”);
thisConnection.Open();//開啟連線
//建立命令物件,並給它提供SQL命令,執行資料庫操作
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = “SELECT CustomerID, CompanyName from Customers”;

// 讀取資料,DataReader是一個輕量級的物件,只能讀取不能更新資料
SqlDataReader thisReader = thisCommand.ExecuteReader();

// DataReader的Read()方法從查詢結果中讀取一行資料,若有則返回TRUE,否則false。
while (thisReader.Read())
{
// Output ID and name columns
Console.WriteLine(“\t{0}\t{1}”,
thisReader[“CustomerID”], thisReader[“CompanyName”]);
}
//關閉讀取器物件和連線物件
thisReader.Close();
thisConnection.Close();
Console.Write(“Program finished, press Enter/Return to continue:”);
Console.ReadLine();

2.用DataSet讀取資料

    SqlConnection thisConnection = new SqlConnection(
      @"Data Source=.\SQLEXPRESS;" +
     @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';" +
      @"Integrated Security=True;Connect Timeout=30;User Instance=true");

        SqlDataAdapter thisAdapter = new SqlDataAdapter(
        "SELECT CustomerID, ContactName FROM Customers", thisConnection);
        DataSet thisDataSet = new DataSet();

//用DataAdapter物件填充DataSet
thisAdapter.Fill(thisDataSet, “Customers”);
foreach (DataRow theRow in thisDataSet.Tables[“Customers”].Rows)
{
Console.WriteLine(theRow[“CustomerID”] + “\t” +
theRow[“ContactName”]);
}

        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

3.更新資料庫
(1)用資料庫中要使用的資料填充DataSet
(2)修改儲存在DataSet中的資料,如更新,插入,刪除
(3)把DataSet中修改的內容返回到資料庫中

SqlConnection thisConnection = new SqlConnection(
@”Data Source=.\SQLEXPRESS;” +
@”AttachDbFilename=’C:\SQL Server 2000 Sample Databases\NORTHWND.MDF’;” +
@”Integrated Security=True;Connect Timeout=30;User Instance=true”);

        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, CompanyName FROM Customers", thisConnection);

        //SqoCommandBuider物件用於負責生成用於更新資料庫的SQL語句,不必自己建立這些語句
        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

        DataSet thisDataSet = new DataSet();

        thisAdapter.Fill(thisDataSet, "Customers");

        Console.WriteLine("name before change: {0}",
             thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);

        thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";
        //Updata()方法自動便利DataTable中的行,以找出需要對資料庫作出的變動。Rows集合中的每個DataRow物件
        //都具有屬性RowState,可以跟蹤此行是否已刪除,新增,修改。所作的任何變化都會反映到資料庫中
        thisAdapter.Update(thisDataSet, "Customers");

        Console.WriteLine("name after change: {0}",
             thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);

        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

4.給資料庫新增行

4.1 不考慮原表中是否已有相同的主鍵
SqlConnection thisConnection = new SqlConnection(
@”Data Source=.\SQLEXPRESS;” +
@”AttachDbFilename=’C:\SQL Server 2000 Sample Databases\NORTHWND.MDF’;” +
@”Integrated Security=True;Connect Timeout=30;User Instance=true”);

        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, CompanyName FROM Customers", thisConnection);

        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

        DataSet thisDataSet = new DataSet();
        thisAdapter.Fill(thisDataSet, "Customers");

        Console.WriteLine("# rows before change: {0}",
                           thisDataSet.Tables["Customers"].Rows.Count);

        DataRow thisRow = thisDataSet.Tables["Customers"].NewRow();
        thisRow["CustomerID"] = "ZACZI";
        thisRow["CompanyName"] = "Zachary Zithers Ltd.";
        thisDataSet.Tables["Customers"].Rows.Add(thisRow);

        Console.WriteLine("# rows after change: {0}",
                          thisDataSet.Tables["Customers"].Rows.Count)

        thisAdapter.Update(thisDataSet, "Customers");

        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

4.2考慮新增的行是否與原表衝突

        SqlConnection thisConnection = new SqlConnection(
            @"Data Source=.\SQLEXPRESS;" +
            @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';" +
            @"Integrated Security=True;Connect Timeout=30;User Instance=true");

        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, CompanyName FROM Customers", thisConnection);

        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

        DataSet thisDataSet = new DataSet();

        thisAdapter.Fill(thisDataSet, "Customers");

        Console.WriteLine("# rows before change: {0}",
             thisDataSet.Tables["Customers"].Rows.Count);
        DataColumn[] keys = new DataColumn[1];
        keys[0] = thisDataSet.Tables["Customers"].Columns["CustomerID"];
        thisDataSet.Tables["Customers"].PrimaryKey = keys;

        DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find("ZACZI");

        if (findRow == null)
        {
            Console.WriteLine("ZACZI not found, will add to Customers table");

            DataRow thisRow = thisDataSet.Tables["Customers"].NewRow();
            thisRow["CustomerID"] = "ZACZI";
            thisRow["CompanyName"] = "Zachary Zithers Ltd.";
            thisDataSet.Tables["Customers"].Rows.Add(thisRow);
            if ((findRow =
                 thisDataSet.Tables["Customers"].Rows.Find("ZACZI")) != null)
            {
                Console.WriteLine("ZACZI successfully added to Customers table");
            }
        }
        else
        {
            Console.WriteLine("ZACZI already present in database");
        }

        thisAdapter.Update(thisDataSet, "Customers");

        Console.WriteLine("# rows after change: {0}",
        thisDataSet.Tables["Customers"].Rows.Count);

        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

5.刪除行

        SqlConnection thisConnection = new SqlConnection(
            @"Data Source=.\SQLEXPRESS;" +
            @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';" +
            @"Integrated Security=True;Connect Timeout=30;User Instance=true");


        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, CompanyName FROM Customers", thisConnection);


        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);


        DataSet thisDataSet = new DataSet();

        thisAdapter.Fill(thisDataSet, "Customers");

        Console.WriteLine("# rows before change: {0}",
             thisDataSet.Tables["Customers"].Rows.Count);

        DataColumn[] keys = new DataColumn[1];
        keys[0] = thisDataSet.Tables["Customers"].Columns["CustomerID"];
        thisDataSet.Tables["Customers"].PrimaryKey = keys;

        DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find("ZACZI");

        if (findRow != null)
        {
            Console.WriteLine("ZACZI already in Customers table");
            Console.WriteLine("Removing ZACZI  . . .");
            //delete()方法並不執行刪除操作,它僅僅標記要刪除的行,delete()方法將行的RowState
            //設定為Deleted,然後Update()就從資料庫中刪除Rows集合中標記為Deleted的行
            findRow.Delete();

            int rowsAffected = thisAdapter.Update(thisDataSet, "Customers");
            Console.WriteLine("Deleted {0} rows.", rowsAffected);

        }

        Console.WriteLine("# rows after change: {0}",
             thisDataSet.Tables["Customers"].Rows.Count);
        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

6.在DataSet中訪問多個表
Ado.net與舊式的相比最大一個優點就是DataSet物件可以跟蹤多個表和它們之間的關係,這裡研究Customers和Orders表。

        SqlConnection thisConnection = new SqlConnection(
            @"Data Source=.\SQLEXPRESS;" +
            @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';" +
            @"Integrated Security=True;Connect Timeout=30;User Instance=true");

        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, CompanyName FROM Customers", thisConnection);

        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

        DataSet thisDataSet = new DataSet();

        SqlDataAdapter custAdapter = new SqlDataAdapter(
             "SELECT * FROM Customers", thisConnection);
        SqlDataAdapter orderAdapter = new SqlDataAdapter(
             "SELECT * FROM Orders", thisConnection);
        custAdapter.Fill(thisDataSet, "Customers");
        orderAdapter.Fill(thisDataSet, "Orders");

        //建立DataRelation物件,得到的關係命名為CustOrders
        DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrders",
             thisDataSet.Tables["Customers"].Columns["CustomerID"],
             thisDataSet.Tables["Orders"].Columns["CustomerID"]);

        foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
        {
            Console.WriteLine("Customer ID: " + custRow["CustomerID"] +
                              " Name: " + custRow["CompanyName"]);
            //指定customers為父表,orders為子表,給定父表中的一行,使用DataRow物件
            //的GetChildRows()方法提取子表中與其對應的所有行
            foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
            {
                Console.WriteLine("  Order ID: " + orderRow["OrderID"]);
            }
        }
        /*
         * to implement writexml as instructed in chapter 24 Writing XML from a DataSet
         * custOrderRel.Nested = true;
         *
         * thisDataSet.WriteXml(@"c:\northwind\nwinddata.xml");
         * Console.WriteLine(
         *   @"Successfully wrote XML output to file c:\northwind\nwinddata.xml");
         */
        /*
         * to implement writexml as instructed in chapter 24 Writing XML from a DataSet*/
         custOrderRel.Nested = true;

          thisDataSet.WriteXml(@"c:\northwind\nwinddata.xml");
          Console.WriteLine(
             @"Successfully wrote XML output to file c:\northwind\nwinddata.xml");


        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();

7.處理更多的關係

        SqlConnection thisConnection = new SqlConnection(
            @"Data Source=.\SQLEXPRESS;" +
            @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';" +
            @"Integrated Security=True;Connect Timeout=30;User Instance=true");

        DataSet thisDataSet = new DataSet();
        SqlDataAdapter custAdapter = new SqlDataAdapter(
             "SELECT * FROM Customers", thisConnection);
        custAdapter.Fill(thisDataSet, "Customers");

        SqlDataAdapter orderAdapter = new SqlDataAdapter(
             "SELECT * FROM Orders", thisConnection);
        orderAdapter.Fill(thisDataSet, "Orders");

        SqlDataAdapter detailAdapter = new SqlDataAdapter(
             "SELECT * FROM [Order Details]", thisConnection);
        detailAdapter.Fill(thisDataSet, "Order Details");

        SqlDataAdapter prodAdapter = new SqlDataAdapter(
             "SELECT * FROM Products", thisConnection);
        prodAdapter.Fill(thisDataSet, "Products");

        DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrders",
                    thisDataSet.Tables["Customers"].Columns["CustomerID"],
                    thisDataSet.Tables["Orders"].Columns["CustomerID"]);

        DataRelation orderDetailRel = thisDataSet.Relations.Add("OrderDetail",
                    thisDataSet.Tables["Orders"].Columns["OrderID"],
                    thisDataSet.Tables["Order Details"].Columns["OrderID"]);

        DataRelation orderProductRel = thisDataSet.Relations.Add(
          "OrderProducts", thisDataSet.Tables["Products"].Columns["ProductID"],
           thisDataSet.Tables["Order Details"].Columns["ProductID"]);

        foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
        {
            Console.WriteLine("Customer ID: " + custRow["CustomerID"]);

            foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
            {
                Console.WriteLine("\tOrder ID: " + orderRow["OrderID"]);
                Console.WriteLine("\t\tOrder Date: " + orderRow["OrderDate"]);

                foreach (DataRow detailRow in
                         orderRow.GetChildRows(orderDetailRel))
                {
                    Console.WriteLine("\t\tProduct: " +
                    detailRow.GetParentRow(orderProductRel)["ProductName"]);
                    Console.WriteLine("\t\tQuantity: " + detailRow["Quantity"]);
                }
            }
        }
        thisConnection.Close();
        Console.Write("Program finished, press Enter/Return to continue:");
        Console.ReadLine();
    }

相關推薦

C# ADO.NET面向對象想法

pub 修改 類型 一個 數據 邏輯思維 增加 分開 清晰 我認為的面向對象就是把各種問題拆分開來 逐一解決, 我想的是先是數據庫,到底有什麽, 然後新建一個類,類裏面先是private的私有的,但是可以有無數個可以連接private的pubilc的屬性 可以在這裏面

C# Ado.net

server cut pwd uil tac work ole 提取 update ADO.NET ADO.NET是.NET數據庫的訪問架構,ADO.NET是數據庫應用程序和數據源之間的溝通的橋樑,提供一個面向對象的數據訪問架構,用來開發數據庫應用程序。提供對象,對象封裝了

[轉]C# ADO.NET SqlDataAdapter中傳遞引數

C# ADO.NET SqlDataAdapter中傳遞引數 ADO.NET的SQL語句中,往往不是靜態的語句,而是需要接受傳遞過來的引數,比如典型的登入功能,需要查詢指定的使用者名稱: string sqlQuery = "SELECT * FROM W_User WHERE UserNa

C# ADO.Net事務處理

SQL Server中的事務可以將多個數據庫增刪改查操作合併為單個工作單元,在操作過程中任何部分出錯都可以滾回已經執行的所有更改.ADO.Net中也提供了事務處理功能,通過ADO.net事務,可以將多個任務繫結在一起,如果所有的任務成功,就提交事務,如果有一個任務失敗,就講

C# ADO.net DataReader資料庫讀取GetString得到NULL值的處理

資料庫中的null和字串中的null是不同型別的值,當讀取時不能直接賦值。 DataReader類封裝了一個方法IsDBNull()來判斷值是不是資料庫中的空(null)值; DataReader reader = cmd.ExecuteReader(); if (rea

C# ADO.NET的五個常用物件及資料庫連線操作

C#中和資料庫連線的操作時開發中必不可少的,而ADO.NET就是其中的關鍵技術之一。常見的ADO.NET有五個常用的物件: SqlConnection 資料庫連線物件 SqlCommand 資料庫命令物件 SqlDataAdapter 資料介面卡 SqlDataRea

C# ADO.NET示例程式

using System.Data;//DataSet在這個名稱空間裡面 using System.Data.SqlClient;//SqlParameter、SqlCommand、SqlDataAdapter都是這個名稱空間裡面SqlParameter[] Param ={

VS C# ADO.NET程式碼連線Access資料庫

在Visual Studio2013 C#中以程式設計方式操作Access資料庫,一般使用OleDb進行連線: 1.首先新增兩個引用(使用using): using System.Data.Ole

C#---ADO.net

Ado.net實際上就是一個用於訪問資料的類組,包括所有的System.data名稱空間以及巢狀的名稱空間,還有System.Xml名稱空間中的一些與資料訪問相關的專用庫,其位於System.data.dll程式集和相關的System.data.xxx.dll程

Java進擊C#——語法之ADO.NET

parameter stmt 深入 真的 讀者 方式 對他 新建 文本 本章簡言 上一章講到關於C#語法的基礎部分。了解相關的基礎部分之後我們就要去了解一下C#是什麽樣子訪問數庫的。C#把訪問數據庫這一部分的知識點叫作ADO.NET。即是JAVA常常講到的JDB

C#回顧 Ado.Net C#連接數據庫進行增、刪、改、查

app linq while 一行 awk col 所有 console value 一、簡介 1、ado.net是一門數據庫訪問技術。 他可以通過程序來操作數據庫 2、類庫 Connection 類 和數據庫交互,必須連接它。連接幫助指明數據庫服務器、數據庫名字、用戶名、

C#後臺獲取數據庫數據--ADO.NET

字符 連接 四個步驟 close info 關閉數據庫 設置 數據 init 關於獲取數據庫中的數據到後臺,可分為4個步驟:1.獲取連接數據庫的字符串;2.創建SqlConnection對象用於打開數據庫;3.創建SqlCommand對象用於執行操作,設置它的一系列屬性即可

c#資料庫操作DataGridView控制元件的使用,ADO.NET

適合初學者,0基礎; 題目: 利用DataGridView控制元件和ADO.NET完成資料的顯示,刪除,修改等; 最終執行的效果如圖所示: 步驟: 1.首先同樣步驟:開啟vs2010,File->new->project->windows Form App

C#對ADO.NET資料庫完成簡單操作

資料庫訪問是程式中應用最普遍的部分。隨著C#和ADO.NET的引入,這種操作變得更簡單。這篇文章將示範四種最基礎的資料庫操作。 ● 讀取資料。其中包括多種資料型別:整型,字串,日期型。 ● 寫資料。如讀資料一樣,我們也需要寫入多種型別的資料。這可以通過SQL語句來完成。

C#】使用ADO.NET訪問Sqlite資料庫,SqliteHelper幫助類

這個就比較簡單了,用過sqlserver的人都知道訪問資料庫的時候一般都會有個SqlHelper的幫助類,這裡就依葫蘆畫瓢寫了個SqliteHelper,很簡單: using System; using System.Collections.Generic

c#操作sql server資料庫(ADO.net基礎)

ado.net提供了豐富的資料庫操作,這些操作可以分為三個步驟: 第一,使用SqlConnection物件連線資料庫; 第二,建立SqlCommand物件,負責SQL語句的執行和儲存過程的呼叫;

C#綜合揭祕——利用泛型與反射更新實體(ADO.NET Entity Framework)

自從ADO.NET Entity Framework面世以來,受到大家的熱捧,它封裝了大量程式碼生成的工具,使用者只需要建立好實體之間的關係,系統就是會為使用者自動成功了Add、Delete、CreateObject、Attach、ToList......等等方法,這些方法

C#學習筆記—ADO.NET

ADO.NET是與C#和.NET Framework一起使用的類集的名稱,用於以關係型的、面向表的格式訪問資料。ADO.NET被整合到.NETFramework中,可用於任何.NET語言,尤其是C#。 ADO.NET包括所有的System.Data名稱空間及其巢狀的名稱空間

c#經典程式設計例項(ado.net基本操作)

一:連線資料庫之查詢學生個數 查詢學生個數程式碼如下: private void button1_Click(object sender, EventArgs e) { string s = "server=.;databas

C#用ado.net訪問EXCEL(含EXCEL2010)的常見問題及解決方法

C#用ado.net訪問EXCEL的常見問題及解決方法,除了像sql server,access常見的資料庫,其實Excel檔案也可以做為資料庫訪問。 ado.net訪問excel的例項: OleDbConnection cn = new OleDbConnectio