答:SqlConnection鏈接、SqlCommand操做、SqlDataReader讀取、DataSet數據管理、
SqlDataAdapter數據適配數據庫
SqlConnection對象緩存
要與數據庫進行交互,您必須與其創建鏈接。該鏈接有助於識別數據庫服務器,數據庫名稱,用戶名,密碼以及鏈接到數據庫所需的其餘參數。命令對象使用鏈接對象,所以它們將知道要在哪一個數據庫上執行命令。服務器
using System; using System.Data; using System.Data.SqlClient; /// <summary> /// 演示如何使用SqlConnection對象 /// </summary> class SqlConnectionDemo { static void Main() { // 1. 實例化鏈接 SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); SqlDataReader rdr = null; try { // 2. 打開鏈接 conn.Open(); // 3. 將鏈接傳遞給命令對象 SqlCommand cmd = new SqlCommand("select * from Customers", conn); // // 4. 使用鏈接 // // 獲取查詢結果 rdr = cmd.ExecuteReader(); //打印每一個記錄的客戶ID while (rdr.Read()) { Console.WriteLine(rdr[0]); } } finally { // 關閉讀取 if (rdr != null) { rdr.Close(); } // 5. 關閉鏈接 if (conn != null) { conn.Close(); } } } }
得到單一值性能
SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);ui
int count = (int)cmd.ExecuteScalar();
清單1. SqlConnection演示this
using System; using System.Data; using System.Data.SqlClient; /// <summary> /// 演示如何使用SqlCommand對象 /// </summary> class SqlCommandDemo { SqlConnection conn; public SqlCommandDemo() { // 實例化鏈接 conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); } // 調用演示SqlCommand功能的方法 static void Main() { SqlCommandDemo scd = new SqlCommandDemo(); Console.WriteLine(); Console.WriteLine("插入前的數據庫"); Console.WriteLine("------------------------"); //使用ExecuteReader方法 scd.ReadData(); //使用ExecuteNonQuery方法插入 scd.Insertdata(); Console.WriteLine(); Console.WriteLine("插入後的數據庫"); Console.WriteLine("------------------------------"); scd.ReadData(); //使用ExecuteNonQuery方法更新 scd.UpdateData(); Console.WriteLine(); Console.WriteLine("更新後的數據庫"); Console.WriteLine("------------------------------"); scd.ReadData(); //使用ExecuteNonQuery方法刪除 scd.DeleteData(); Console.WriteLine(); Console.WriteLine("刪除後的數據庫"); Console.WriteLine("------------------------------"); scd.ReadData(); //使用ExecuteScalar方法 int numberOfRecords = scd.GetNumberOfRecords(); Console.WriteLine(); Console.WriteLine("記錄數: {0}", numberOfRecords); } /// <summary> /// 使用ExecuteReader方法 /// </summary> public void ReadData() { SqlDataReader rdr = null; try { //打開鏈接 conn.Open(); // 1.使用查詢和鏈接實例化一個新命令 SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); // 2.調用Execute reader獲取查詢結果 rdr = cmd.ExecuteReader(); // 打印每一個記錄的類別名稱 while (rdr.Read()) { Console.WriteLine(rdr[0]); } } finally { // 關閉讀取器 if (rdr != null) { rdr.Close(); } // 關閉鏈接 if (conn != null) { conn.Close(); } } } /// <summary> /// 使用ExecuteNonQuery方法用於插入 /// </summary> public void Insertdata() { try { // 打開鏈接 conn.Open(); // 準備命令串 string insertString = @"insert into Categories (CategoryName, Description) values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')"; // 1. 使用查詢和鏈接實例化一個新命令 SqlCommand cmd = new SqlCommand(insertString, conn); // 2. 調用ExecuteNonQuery發送命令 cmd.ExecuteNonQuery(); } finally { // 關閉鏈接 if (conn != null) { conn.Close(); } } } /// <summary> /// 使用ExecuteNonQuery方法用於更新 /// </summary> public void UpdateData() { try { // 打開鏈接 conn.Open(); // 準備命令字符串 string updateString = @"update Categories set CategoryName = 'Other'where CategoryName = 'Miscellaneous'"; // 1. 僅使用命令文本實例化新命令 SqlCommand cmd = new SqlCommand(updateString); // 2. 設置鏈接屬性 cmd.Connection = conn; // 3. 調用ExecuteNonQuery發送命令 cmd.ExecuteNonQuery(); } finally { // 關閉鏈接 if (conn != null) { conn.Close(); } } } /// <summary> /// 使用ExecuteNonQuery刪除方法 /// </summary> public void DeleteData() { try { // 打開鏈接 conn.Open(); // 準備命令字符串 string deleteString = @" delete from Categories where CategoryName = 'Other'"; // 1. 實例化一個新命令 SqlCommand cmd = new SqlCommand(); // 2. 設置CommandText屬性 cmd.CommandText = deleteString; // 3. 設置Connection屬性 cmd.Connection = conn; // 4.調用ExecuteNonQuery發送命令 cmd.ExecuteNonQuery(); } finally { // 關閉鏈接 if (conn != null) { conn.Close(); } } } /// <summary> /// 使用ExecuteScalar方法 /// </summary> /// <returns>記錄數</returns> public int GetNumberOfRecords() { int count = -1; try { // 打開鏈接 conn.Open(); // 1. 實例化一個新命令 SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn); // 2. 調用ExecuteScalar發送命令 count = (int)cmd.ExecuteScalar(); } finally { // 關閉鏈接 if (conn != null) { conn.Close(); } } return count; } }
SqlCommand對象spa
與數據庫交互的過程意味着您必須指定要發生的操做。這是經過命令對象完成的。您使用命令對象將SQL語句發送到數據庫。命令對象使用鏈接對象來肯定要與哪一個數據庫通訊。您能夠單獨使用命令對象,直接執行命令,或將命令對象的引用分配給SqlDataAdapter,SqlDataAdapter包含一組處理一組數據的命令,以下所述。code
// 1. 使用查詢和鏈接實例化一個新命令orm
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); // 2. 調用Execute reader獲取查詢結果 SqlDataReader rdr = cmd.ExecuteReader();
插入數據對象
string insertString = @"insert into Categories(CategoryName, Description)values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')"; SqlCommand cmd = new SqlCommand(insertString, conn); cmd.ExecuteNonQuery();
更新數據
// 定義命令字符串 string updateString = @"update Categories set CategoryName = 'Other'where CategoryName = 'Miscellaneous'"; // 1. 僅使用命令文本實例化新命令 SqlCommand cmd = new SqlCommand(updateString); // 2. 設置Connection屬性 cmd.Connection = conn; // 3. 調用ExecuteNonQuery發送命令 cmd.ExecuteNonQuery();
刪除數據
// 準備命令串 string deleteString = @"delete from Categories where CategoryName = 'Other'"; // 1. .實例化一個新命令 SqlCommand cmd = new SqlCommand(); // 2.設置CommandText屬性 cmd.CommandText = deleteString; // 3. 設置Connection屬性 cmd.Connection = conn; // 4. 調用ExecuteNonQuery發送命令 cmd.ExecuteNonQuery();
SqlDataReader對象
許多數據操做要求您只獲取用於讀取的數據流。數據讀取器對象容許您從命令對象獲取SELECT語句的結果。出於性能緣由,從數據讀取器返回的數據是僅限快進的數據流。這意味着您只能以順序方式從流中提取數據這對速度有利,但若是您須要操做數據,那麼DataSet是一個更好的對象。
建立SqlDataReader對象
SqlDataReader rdr = cmd.ExecuteReader();
數據讀取
while (rdr.Read()) { // 獲取每一個列字符串的結果 string contact = (string)rdr["ContactName"]; string company = (string)rdr["CompanyName"]; string city = (string)rdr["City"]; // 打印出結果 Console.Write("{0,-25}", contact); Console.Write("{0,-20}", city); Console.Write("{0,-25}", company); Console.WriteLine(); }
整理
try { // 數據訪問代碼 } finally { // 3. 關閉讀取器 if (rdr != null) { rdr.Close(); } // 關閉鏈接 }
清單1:使用SqlDataReader
using System; using System.Data; using System.Data.SqlClient; namespace Lesson04 { class ReaderDemo { static void Main() { ReaderDemo rd = new ReaderDemo(); rd.SimpleRead(); } public void SimpleRead() { // 聲明SqlDataReader中,這是在使用//兩個try塊和finally塊 SqlDataReader rdr = null; // 建立鏈接對象 SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); // 建立一個命令對象 SqlCommand cmd = new SqlCommand("select * from Customers", conn); try { // 打開鏈接 conn.Open(); // 1. 獲取SqlDataReader的實例 rdr = cmd.ExecuteReader(); // 打印一組列標題 Console.WriteLine("Contact Name City Company Name"); Console.WriteLine("--------------------------------"); // 2. 打印每一個必要的列記錄 while (rdr.Read()) { // 獲取每一個列字符串的結果 string contact = (string)rdr["ContactName"]; string company = (string)rdr["CompanyName"]; string city = (string)rdr["City"]; // 打印出結果 Console.Write("{0,-25}", contact); Console.Write("{0,-20}", city); Console.Write("{0,-25}", company); Console.WriteLine(); } } finally { // 3. 關閉讀取器 if (rdr != null) { rdr.Close(); } // 關閉鏈接 if (conn != null) { conn.Close(); } } } } }
DataSet對象
DataSet對象是數據的內存表示。它們包含多個Datatable對象,這些對象包含列和行,就像普通的數據庫表同樣。您甚至能夠定義表之間的關係以建立父子關係。DataSet專門用於幫助管理內存中的數據,並在這種狀況有意義時支持對數據的斷開操做。DataSet是全部數據提供程序使用的對象,這就是它沒有數據提供程序特定前綴的緣由。
SqlDataAdapter對象
有時,您使用的數據主要是隻讀的,您不多須要對基礎數據源進行更改。某些狀況還要求在內存中緩存數據,以最大限度地減小不更改數據的數據庫調用次數。經過數據適配器,您能夠經過幫助以斷開鏈接模式管理數據來輕鬆完成這些任務。數據適配器在讀取數據時填充DataSet對象,並在將更改持久保存到數據庫時在單個批處理中寫入。數據適配器包含對鏈接對象的引用,並在讀取或寫入數據庫時自動打開和關閉鏈接。此外,數據適配器包含對數據的SELECT,INSERT,UPDATE和DELETE操做的命令對象引用。您將爲DataSet中的每一個表定義一個數據適配器,它將爲您處理與數據庫的全部通訊。您須要作的就是告訴數據適配器什麼時候加載或寫入數據庫。
建立DataSet對象
DataSet dsCustomers = new DataSet();
建立SqlDataAdapter
SqlDataAdapter daCustomers = new SqlDataAdapter("select CustomerID, CompanyName from Customers", conn);
使用SqlCommandBuilder向SqlDataAdapter添加命令的方法:
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);
填充DataSet
daCustomers.Fill(dsCustomers, "Customers");
使用DataSet
dgCustomers.DataSource = dsCustomers; dgCustomers.DataMember = "Customers";
更新更改
daCustomers.Update(dsCustomers, "Customers");
完整演示:
using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Windows.Forms; class DisconnectedDataform : Form { private SqlConnection conn; private SqlDataAdapter daCustomers; private DataSet dsCustomers; private DataGrid dgCustomers; private const string tableName = "Customers"; //使用DataGrid和Button public 初始化表單 public DisconnectedDataform() { // 填充數據集 Initdata(); // 設置datagrid dgCustomers = new DataGrid(); dgCustomers.Location = new Point(5, 5); dgCustomers.Size = new Size( this.ClientRectangle.Size.Width - 10, this.ClientRectangle.Height - 50); dgCustomers.DataSource = dsCustomers; dgCustomers.DataMember = tableName; //建立更新按鈕 Button btnUpdate = new Button(); btnUpdate.Text = "Update"; btnUpdate.Location = new Point( this.ClientRectangle.Width / 2 - btnUpdate.Width / 2, this.ClientRectangle.Height - (btnUpdate.Height + 10)); btnUpdate.Click += new EventHandler(btnUpdateClicked); //確保控件出如今表單 Controls.AddRange(new Control[] { dgCustomers, btnUpdate }); } //設置ADO.NET對象 public void Initdata() { //實例化鏈接 conn = new SqlConnection( "Server=(local);DataBase=Northwind;Integrated Security=SSPI"); // 1. 實例化一個新的DataSet dsCustomers = new DataSet(); // 2. 使用select命令和鏈接 daCustomers = new SqlDataAdapter( "select CustomerID, CompanyName from Customers", conn); // 3.填寫插入,更新和刪除命令 SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers); // 4. 填充數據集 daCustomers.Fill(dsCustomers, tableName); } // 單擊更新按鈕 public void btnUpdateClicked(object sender, EventArgs e) { // 將更改寫回DataBase daCustomers.Update(dsCustomers, tableName); } // 啓動Windows窗體 static void Main() { Application.Run(new DisconnectedDataForm()); } }