ADO.NET基礎知識詳解
ADO.NET是微軟提供的一種數(shù)據(jù)庫訪問技術。
ADO.NET為不同類型的數(shù)據(jù)源提供了不同的數(shù)據(jù)提供程序?qū)ο?
數(shù)據(jù)提供程序 | 說明 |
---|---|
SQL Server 數(shù)據(jù)提供程序 | 提供對Microsoft SQL Server中數(shù)據(jù)的訪問,使用System.Data.SqlClient命名空間。 |
OLE 數(shù)據(jù)提供程序 | 提供對使用OLE DB公開的數(shù)據(jù)源(如Access、Excel等)中數(shù)據(jù)的訪問,使用System.Data.oleDb命名空間。 |
ODBC 數(shù)據(jù)提供程序 | 提供對使用ODBC公開的數(shù)據(jù)源中數(shù)據(jù)的訪問,使用System.Data.Odbc命名空間。 |
數(shù)據(jù)提供程序中包含了ADO.NET的四個核心對象:
對象 | 說明 |
---|---|
Connection | 建立與特定數(shù)據(jù)源的連接 |
Command | 對數(shù)據(jù)源執(zhí)行命令 |
DataReader | 從數(shù)據(jù)源中讀取只進只讀的數(shù)據(jù)流 |
DataAdapter | 使用數(shù)據(jù)源填充DataSet并支持更新 |
ADO.NET提供兩種方式訪問數(shù)據(jù)庫:
連接式訪問:整個操作過程中需要保持數(shù)據(jù)庫連接。
斷開式訪問:只需要在執(zhí)行數(shù)據(jù)庫命令時保持數(shù)據(jù)庫連接。
一、使用DataReader讀取數(shù)據(jù)
使用DataReader讀取數(shù)據(jù)屬于連接式讀取,只能只進的一行一行讀取數(shù)據(jù),并且不能改變數(shù)據(jù),如需要改變數(shù)據(jù),必須重新執(zhí)行insert,update,delete等sql語句來改變數(shù)據(jù)。
示例:使用DataReader讀取數(shù)據(jù)在ListView控件顯示:
此示例的測試數(shù)據(jù)如下:
create table Member ( MemberId int primary key identity(1,1), MemberAccount nvarchar(20) unique check(len(MemberAccount) between 6 and 12), MemberPwd nvarchar(20), MemberName nvarchar(20), MemberPhone nvarchar(20) ) insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('liubei','123456','劉備','4659874564') insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('guanyu','123456','關羽','42354234124') insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('zhangfei','123456','張飛','41253445') insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('zhangyun','123456','趙云','75675676547') insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('machao','123456','馬超','532523523')
此示例代碼如下:
在編寫代碼之前需要進行ListView控件的編輯列操作,并且將視圖模式切換成Details模式。
private void Form1_Load(object sender, EventArgs e) { //1-編寫連接字符串(windows方式連接) string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-創(chuàng)建連接對象,打開數(shù)據(jù)庫連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member"; //4-定義執(zhí)行命令的對象執(zhí)行命令 SqlCommand cmd = new SqlCommand(sql, conn); //5-利用DataReader讀取數(shù)據(jù) SqlDataReader rd = cmd.ExecuteReader(); while (rd.Read()) { ListViewItem item = new ListViewItem(rd["MemberId"].ToString()); item.SubItems.Add(rd["MemberAccount"].ToString()); item.SubItems.Add(rd["MemberPwd"].ToString()); item.SubItems.Add(rd["MemberName"].ToString()); item.SubItems.Add(rd["MemberPhone"].ToString()); this.listView1.Items.Add(item); } rd.Close(); //顯示人數(shù) cmd.CommandText = "select count(*) from Member"; int count = (int)cmd.ExecuteScalar(); this.lblCount.Text = "會員人數(shù):" + count; conn.Close(); }
二、使用DataAdapter的方式抽取數(shù)據(jù)
DataSet是特意為獨立于所有數(shù)據(jù)源的數(shù)據(jù)訪問而設計的,可以理解成內(nèi)存中的數(shù)據(jù)庫。
在支持ADO.NET的斷開式、分布式數(shù)據(jù)方案中起著重要的作用。
DataSet是數(shù)據(jù)駐留在內(nèi)存中的表現(xiàn)形式,無論是什么數(shù)據(jù)源,它都可以提供一致的編程模型。
DataSet支持改變數(shù)據(jù)然后回傳給數(shù)據(jù)庫。
示例:使用DataAdapter抽取數(shù)據(jù)到DataTable中,在DataGridView中進行顯示
此示例的測試數(shù)據(jù)與文檔第一部分測試數(shù)據(jù)相同。
此示例代碼如下:
在編寫代碼之前需要對DataGridView控件進行編輯列操作。
設置DataGridView控件的AllowUserToAddRows=False實現(xiàn)清楚最后一個空行,SelectionMode=FullRowSelect實現(xiàn)整行選中模式,用戶體驗更好。
//窗體加載事件 private void Form1_Load(object sender, EventArgs e) { //1-定義連接字符串 //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member"; //4-數(shù)據(jù)適配器抽取信息 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); //數(shù)據(jù)表格 adp.Fill(dt); this.dataGridView1.AutoGenerateColumns = false; //自動列取消 this.dataGridView1.DataSource = dt; //顯示人數(shù) adp.SelectCommand.CommandText = "select count(*) from Member"; int count = (int)adp.SelectCommand.ExecuteScalar(); this.lblCount.Text = "會員人數(shù):" + count; conn.Close(); } //修改數(shù)據(jù)后跟新數(shù)據(jù)庫的按鈕事件 private void btUpdate_Click(object sender, EventArgs e) { //1-定義連接字符串 //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member"; //4-數(shù)據(jù)適配器抽取信息 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); //數(shù)據(jù)表格 adp.Fill(dt); //添加一條數(shù)據(jù) DataRow dr = dt.NewRow(); dr["MemberAccount"] = "weiyan"; dr["MemberPwd"] = "123456"; dr["MemberName"] = "魏延"; dr["MemberPhone"] = "15352565585"; dt.Rows.Add(dr); //修改一條數(shù)據(jù) dt.Rows[1]["MemberPwd"] = "654321"; //刪除一條數(shù)據(jù) dt.Rows[4].Delete(); //跟新數(shù)據(jù)到數(shù)據(jù)庫 SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(adp); adp.Update(dt); //確認DataTable的數(shù)據(jù)變化,并且重新綁定到控件 dt.AcceptChanges(); this.dataGridView1.DataSource = dt; MessageBox.Show("數(shù)據(jù)跟新成功!"); }
三、非查詢操作
非查詢操作分為"添加","刪除","修改"操作,這些操作處理sql語句不同,其他編碼是一樣的,所以在此文檔中以添加操作為例介紹非查詢操作。
示例:添加會員信息
此示例的測試數(shù)據(jù)與文檔第一部分測試數(shù)據(jù)相同。
此示例中通過兩種方式添加數(shù)據(jù):
- (1)使用DataAdapter的command跟新數(shù)據(jù)
- (2)直接使用SqlCommand對象跟新數(shù)據(jù)
此示例代碼如下:
//方案一:使用DataAdapter的command跟新數(shù)據(jù) private void btAdd1_Click(object sender, EventArgs e) { //1-定義連接字符串 //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = string.Format("insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('{0}', '{1}', '{2}', '{3}')" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text); //4-數(shù)據(jù)適配器 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); //執(zhí)行sql語句 int rowCount = adp.SelectCommand.ExecuteNonQuery(); conn.Close(); if(rowCount == 1) MessageBox.Show("添加成功!"); else MessageBox.Show("添加失敗!"); } //方案二:直接使用SqlCommand對象跟新數(shù)據(jù) private void btAdd2_Click(object sender, EventArgs e) { //1-編寫連接字符串(windows方式連接) //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-創(chuàng)建連接對象,打開數(shù)據(jù)庫連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = string.Format("insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('{0}', '{1}', '{2}', '{3}')" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text); //4-定義執(zhí)行命令的對象執(zhí)行命令 SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("添加成功!"); else MessageBox.Show("添加失敗!"); }
四、一個窗體中實現(xiàn)會員信息的增加,刪除,修改,查詢操作
此示例的測試數(shù)據(jù)與文檔第一部分測試數(shù)據(jù)相同。
業(yè)務需求:
- (1)窗體加載的時候顯示數(shù)據(jù)。
- (2)輸入字段內(nèi)容,點擊新增按鈕,可以添加數(shù)據(jù)
- (3)鼠標選中一行,右鍵彈出刪除菜單,可以刪除數(shù)據(jù)
- (4)鼠標選中一行,將會員信息在右側(cè)文本框中顯示,重新編輯后可以點擊修改按鈕實現(xiàn)數(shù)據(jù)的修改
代碼如下:
綁定數(shù)據(jù)的通用方法:
//綁定數(shù)據(jù)的方法 private void BindData() { //1-定義連接字符串 //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member"; //4-數(shù)據(jù)適配器抽取信息 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); //數(shù)據(jù)表格 adp.Fill(dt); this.dataGridView1.AutoGenerateColumns = false; //自動列取消 this.dataGridView1.DataSource = dt; conn.Close(); }
窗體加載事件代碼:
//窗體加載事件 private void Form1_Load(object sender, EventArgs e) { BindData(); }
新增按鈕的點擊事件代碼:
//添加信息按鈕事件 private void btAdd_Click(object sender, EventArgs e) { //1-編寫連接字符串(windows方式連接) //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-創(chuàng)建連接對象,打開數(shù)據(jù)庫連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = string.Format("insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('{0}', '{1}', '{2}', '{3}')" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text); //4-定義執(zhí)行命令的對象執(zhí)行命令 SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("添加成功!"); else MessageBox.Show("添加失敗!"); BindData(); }
DataGridView控件的點擊事件代碼:
//網(wǎng)格控件的點擊事件 private void dataGridView1_Click(object sender, EventArgs e) { //當AllowUserToAddRows=True的時候,防止用戶選擇最后一個空行 if (this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString().Equals("")) { MessageBox.Show("請正確選擇!"); return; } int memId = int.Parse(this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); //MessageBox.Show(memId.ToString()); //1-定義連接字符串 string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member where MemberId = " + memId; //-抽取數(shù)據(jù) SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); adp.Fill(dt); conn.Close(); this.txtAccount.Text = dt.Rows[0]["MemberAccount"].ToString(); this.txtPwd.Text = dt.Rows[0]["MemberPwd"].ToString(); this.txtNickName.Text = dt.Rows[0]["MemberName"].ToString(); this.txtPhone.Text = dt.Rows[0]["MemberPhone"].ToString(); }
修改按鈕的點擊事件代碼:
//修改按鈕的點擊事件 private void btUpdate_Click(object sender, EventArgs e) { int memId = int.Parse(this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = string.Format("update Member set MemberAccount='{0}',MemberPwd='{1}',MemberName='{2}',MemberPhone='{3}' where MemberId='{4}'" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text, memId); SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("修改成功!"); else MessageBox.Show("修改失敗!"); BindData(); }
//刪除菜單的點擊事件代碼:
//刪除信息彈出菜單事件 private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult r = MessageBox.Show("您確定要刪除嗎?", "****系統(tǒng)", MessageBoxButtons.YesNo); if (r == System.Windows.Forms.DialogResult.No) { return; } int memId = int.Parse(this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = "delete from Member where MemberId = " + memId; SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("刪除成功!"); else MessageBox.Show("刪除失敗!"); BindData(); }
五、多個窗體中實現(xiàn)會員信息的增加,刪除,修改,查詢操作
此示例的測試數(shù)據(jù)與文檔第一部分測試數(shù)據(jù)相同。
業(yè)務需求:
- (1)窗體加載的時候顯示數(shù)據(jù)。
- (2)點擊"添加數(shù)據(jù)"按鈕,彈出新窗體,在新窗體中進行數(shù)據(jù)的添加,添加完成后自動刷新表格數(shù)據(jù)。
- (3)鼠標選中一行,右鍵彈出刪除菜單,可以刪除數(shù)據(jù)
- (4)鼠標選中一行,點擊"編輯數(shù)據(jù)"按鈕,彈出新窗體,在新窗體中進行數(shù)據(jù)修改,修改后自動刷新表格數(shù)據(jù)。
實現(xiàn)步驟如下:
(1)查詢窗體顯示數(shù)據(jù)代碼:
//綁定數(shù)據(jù)的方法 public void BindData() { //1-定義連接字符串 //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member"; //4-數(shù)據(jù)適配器抽取信息 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); //數(shù)據(jù)表格 adp.Fill(dt); this.dataGridView1.AutoGenerateColumns = false; //自動列取消 this.dataGridView1.DataSource = dt; conn.Close(); } private void FrmSelect_Load(object sender, EventArgs e) { BindData(); }
(2)"刪除"菜單代碼:
private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult r = MessageBox.Show("您確定要刪除嗎?", "****系統(tǒng)", MessageBoxButtons.YesNo); if (r == System.Windows.Forms.DialogResult.No) { return; } int memId = int.Parse(this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = "delete from Member where MemberId = " + memId; SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("刪除成功!"); else MessageBox.Show("刪除失敗!"); BindData(); }
(3)會員添加窗體代碼:
private void btAdd_Click(object sender, EventArgs e) { //1-編寫連接字符串(windows方式連接) //string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-編寫連接字符串(sql用戶名密碼方式連接) string connStr = "server=.;database=DBTEST;uid=sa;pwd=123456"; //2-創(chuàng)建連接對象,打開數(shù)據(jù)庫連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = string.Format("insert into Member(MemberAccount,MemberPwd,MemberName,MemberPhone) values('{0}', '{1}', '{2}', '{3}')" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text); //4-定義執(zhí)行命令的對象執(zhí)行命令 SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("添加成功!"); else MessageBox.Show("添加失敗!"); //刷新查詢窗體數(shù)據(jù)并關閉當前窗體 ((FrmSelect)this.Owner).BindData(); this.Close(); }
(4)會員編輯窗體代碼:
public int MemId { get; set; } //接受外部傳遞過來的會員編號 //綁定會員詳情到文本框 private void BindDetail() { //1-定義連接字符串 string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; //2-定義連接對象,打開連接 SqlConnection conn = new SqlConnection(connStr); conn.Open(); //3-編寫sql語句 string sql = "select * from Member where MemberId = " + this.MemId; //-抽取數(shù)據(jù) SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); adp.Fill(dt); conn.Close(); this.txtAccount.Text = dt.Rows[0]["MemberAccount"].ToString(); this.txtPwd.Text = dt.Rows[0]["MemberPwd"].ToString(); this.txtNickName.Text = dt.Rows[0]["MemberName"].ToString(); this.txtPhone.Text = dt.Rows[0]["MemberPhone"].ToString(); } private void FrmEdit_Load(object sender, EventArgs e) { BindDetail(); } private void btUpdate_Click(object sender, EventArgs e) { string connStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBTEST;Data Source=."; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = string.Format("update Member set MemberAccount='{0}',MemberPwd='{1}',MemberName='{2}',MemberPhone='{3}' where MemberId='{4}'" , this.txtAccount.Text, this.txtPwd.Text, this.txtNickName.Text, this.txtPhone.Text, this.MemId); SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.ExecuteNonQuery(); conn.Close(); if (rowCount == 1) MessageBox.Show("修改成功!"); else MessageBox.Show("修改失敗!"); //刷新查詢窗體數(shù)據(jù)并關閉當前窗體 ((FrmSelect)this.Owner).BindData(); this.Close(); }
(5)查詢窗體"添加數(shù)據(jù)"和"編輯數(shù)據(jù)"按鈕的代碼:
private void btAdd_Click(object sender, EventArgs e) { FrmAdd frm = new FrmAdd(); frm.Owner = this; frm.Show(); } private void btEdit_Click(object sender, EventArgs e) { if (this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString().Equals("")) { MessageBox.Show("請正確選擇!"); return; } int memId = int.Parse(this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); FrmEdit frm = new FrmEdit(); frm.MemId = memId; frm.Owner = this; frm.Show(); }
到此這篇關于ADO.NET基礎知識的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
為大家經(jīng)常為md5加密過的常用admin,admin888,0000密碼
為大家經(jīng)常為md5加密過的常用admin,admin888,0000密碼...2007-10-10ASP.NET?Core中Razor頁面的Handlers處理方法詳解
本文詳細講解了ASP.NET?Core中Razor頁面的Handlers處理方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02