祥解Visual C#資料庫編程

來源:互聯網
上載者:User
visual|編程|資料|資料庫 關於資料庫編程,微軟提供了一個統一的資料對象訪問模型,在Visual Studio6.0中稱為ADO,在.NET中則統一為ADO.NET,掌握ADO.NET就等於掌握了資料庫編程的核心。
  針對資料庫編程始終是程式設計語言的一個重要方面的內容,也是一個痛點。資料庫編程的內容十分豐富,但最為基本編程的也就是那麼幾點,譬如:串連資料庫、得到需要的資料和針對資料記錄的瀏覽、刪除、修改、插入等操作。其中又以後面針對資料記錄的資料操作為重點。本文就來著重探討一下Visual C#資料庫基本編程,即:如何瀏覽記錄、修改記錄、刪除記錄和插入記錄。

  一.程式設計和啟動並執行環境設定:

  (1).視窗2000伺服器版

  (2).Microsoft Data Acess Component 2.6 以上版本 ( MDAC 2.6 )

  (3)..Net FrameWork SDK Beta 2

  為了更清楚的說明問題,在資料庫的選用上,採用了當前比較典型的資料庫,一個是本機資料庫Access 2000,另外一個是遠端資料庫Sql Server 2000。其中本機資料庫名稱為"db.mdb",在其中定義了一張資料表"person","person"表的資料結構如下表:

欄位名稱 欄位類型 欄位意思
id 數字 序號
xm 文本 姓名
xb 文本 性別
nl 文本 年齡
zip 文本 郵遞區號

  遠端資料庫Sql Server 2000的資料庫伺服器名稱為"Server1",資料庫名稱為"Data1",登陸的ID為"sa",口令為空白,在資料庫也定義了一張"person"表,資料結構如上表。
二.如何瀏覽資料:

  在《Visual C#的資料繫結》中,已經瞭解了如何把資料集中的某些欄位綁定到WinForm組件的某個屬性上,這樣程式員就可以根據以WinForm組件的來定製資料顯示的形式,並且此時的WinForm組件顯示內容就可以隨著記錄指標的變化而改變。至此可見,瀏覽資料記錄的關鍵就是如何改變記錄指標。要實現這種操作,就要使用到BindingManagerBase類,此類的主要作用是管理對於那些實現了對同一個資料來源進行綁定的對象。說的具體些,就是能夠使得Windows表單上的已經對同一資料來源進行資料繫結的組件保持同步。在BindingManagerBase類中定義了一個屬性"Position",通過這個屬性就可以改變BindingManagerBase對象中的資料指標。建立BindingManagerBase對象必須要使用到BindingContext類,其實每一個由Control類中繼承而得到的對象,都有單一的BindingContext對象,在大多數建立表單中實現資料繫結組件的BindingManagerBase對象是使用Form類的BindingContext來得到。下列代碼是以Access 2000資料庫為模型,建立的一個名稱為"myBind"的BindingManagerBase對象。

//建立一個 OleDbConnection
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM person " ;
file://建立一個 DataSet
myDataSet = new DataSet ( ) ;

myConn.Open ( ) ;
file://用 OleDbDataAdapter 得到一個資料集
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
file://把Dataset綁定books資料表
myCommand.Fill ( myDataSet , "person" ) ;
file://關閉此OleDbConnection
myConn.Close ( ) ;
myBind = this.BindingContext [ myDataSet , "person" ] ;

  下列代碼是以Sql Server 2000資料庫為模型,建立一個名稱為"myBind"的BindingManagerBase對象。

// 設定資料連線字串,此字串的意思是開啟Sql server資料庫,伺服器名稱為server1,資料庫為data1
string strCon = "Provider = SQLOLEDB.1 ; Persist Security Info = False ; User ID = sa ; Initial Catalog = data1 ; Data Source = server1 " ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
myConn.Open ( ) ;
string strCom = " SELECT * FROM person " ;
file://建立一個 DataSet
myDataSet = new DataSet ( ) ;
file://用 OleDbDataAdapter 得到一個資料集
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
file://把Dataset綁定person資料表
myCommand.Fill ( myDataSet , " person " ) ;
file://關閉此OleDbConnection
myConn.Close ( ) ;
myBind = this.BindingContext [ myDataSet , "person" ] ;

  得到了是同一資料來源的BindingManagerBase對象,通過改變此對象的"Position"屬性值,這樣綁定資料的組件顯示的資料就隨之變化,從而實現導航資料記錄。

  < I > .導覽按鈕"上一條"實現方法:

protected void GoPrevious ( object sender , System.EventArgs e )
{
if ( myBind.Position == 0 )
MessageBox.Show ( "已經到了第一條記錄!" , "資訊提示!" , MessageBoxButtons.OK , MessageBoxIcon.Information ) ;
else
myBind.Position -= 1 ;
}

  < II > . 導覽按鈕"下一條"實現方法:

protected void GoNext ( object sender , System.EventArgs e )
{
if ( myBind.Position == myBind.Count -1 )
MessageBox.Show ( "已經到了最後一條記錄!", "資訊提示!" , MessageBoxButtons.OK , MessageBoxIcon.Information ) ;
else
myBind.Position += 1 ;
}

  < III > . 導覽按鈕"至尾"實現方法:

protected void GoLast ( object sender , System.EventArgs e )
{
myBind.Position = myBind.Count - 1 ;
}
< IV > . 導覽按鈕"至首"實現方法:
protected void GoFirst ( object sender , System.EventArgs e )
{
myBind.Position = 0 ;
}

  注釋:"Count"是BindingManagerBase對象的另外一個重要的屬性,是資料集記錄的總數。
三.實現刪除記錄:

  在對資料記錄進行操作的時候,有二點必須十分清晰:

  其一:在對資料記錄進行操作的時候,我想有一些程式員一定有這樣一個疑惑,當對資料庫伺服器請求資料集的時候,就會產生"DataSet"對象,用以管理資料集,這樣如果這些對資料庫伺服器的請求非常多,同樣也就會產生很多的"DataSet"對象,達到一定時候必然會使得資料庫伺服器崩潰。這種想法是自然的,但和實際並不相符,因為"DataSet"對象並不是在伺服器端產生的,而是在用戶端產生的。所以面對眾多的資料請求的時候對資料庫伺服器的影響並不十分太大。

  其二:記得在用Delphi編寫三層資料模型的時候的,每一次對資料庫的修改其實只是對第二層產生的資料集的修改,要真正修改資料庫,還必須調用一個另外的方法。在用ADO.NET處理資料庫的時候,雖然處理的直接對象是資料庫,但此時"DataSet"對象中的內容並沒有隨之改變,而繫結資料組件顯示的資料又來源於"DataSet"對象,這樣就會產生一個錯覺,就是修改了的記錄並沒有修改掉,刪除的記錄並沒有刪除掉。所以對資料記錄進行操作的時候,在修改資料庫後,還要對"DataSet"對象進行必要的修改,這樣才能保證"DataSet"對象和資料庫內容一致、同步。下面代碼是刪除當前綁定組件顯示的記錄的程式碼,此代碼是以Access 2000資料庫為模板的:

protected void Delete_record ( object sender , System.EventArgs e )
{
DialogResult r = MessageBox.Show ( "是否刪除目前記錄!" , "刪除目前記錄!" , MessageBoxButtons.YesNo , MessageBoxIcon.Question ) ;
int ss = ( int ) r ;
  if ( ss == 6 ) // 按動"確定"按鈕
{
try{
file://串連到一個資料庫
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb " ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
myConn.Open ( ) ;
string strDele = "DELETE FROM person WHERE id= " + t_id.Text ;
OleDbCommand myCommand = new OleDbCommand ( strDele , myConn ) ;
file://從資料庫中刪除指定記錄
myCommand.ExecuteNonQuery ( ) ;
file://從DataSet中刪除指定記錄
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . Delete ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
myConn.Close ( ) ;
}
catch ( Exception ed )
{
MessageBox.Show ( "刪除記錄錯誤資訊: " + ed.ToString ( ) , "錯誤!" ) ;
}
}
}

四.插入資料記錄:

  對資料庫進行插入記錄操作和刪除記錄操作基本的思路是一致的,就是通過ADO.NET首先插入資料記錄到資料庫,然後對"DataSet"對象進行必要的修改。下列代碼就是以Access 2000資料庫為模型修改目前記錄的代碼:

protected void Update_record ( object sender , System.EventArgs e )
{
int i = myBind.Position ;
try{
file://串連到一個資料庫
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb " ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
myConn.Open ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . BeginEdit ( ) ;
file://從資料庫中修改指定記錄
string strUpdt = " UPDATE person SET xm = '"
+ t_xm.Text + "' , xb = '"
+ t_xb.Text + "' , nl = "
+ t_nl.Text + " , zip = "
+ t_books.Text + " WHERE id = " + t_id.Text ;
OleDbCommand myCommand = new OleDbCommand ( strUpdt , myConn ) ;
myCommand.ExecuteNonQuery ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . EndEdit ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
myConn.Close ( ) ;
}
catch ( Exception ed )
{
MessageBox.Show ( "修改指定記錄錯誤: " + ed.ToString ( ) , "錯誤!" ) ;
}
myBind.Position = i ;
}

  由於對Sql Server 2000資料記錄修改操作和Access 2000資料記錄修改操作的差異只在於不同的資料連結,具體的代碼可以參考"刪除資料記錄"中的代碼,在這裡就不提供了。
五.插入資料記錄:

  和前面二種操作在思路是一致的,就是通過ADO.NET首先插入資料記錄到資料庫,然後對"DataSet"對象進行必要的修改。下列代碼就是以Access 2000資料庫為模型插入一條資料記錄的代碼

protected void Insert_record ( object sender , System.EventArgs e )
{
try
{
file://判斷所有欄位是否添完,添完則執行,反之彈出提示
if ( t_id.Text != "" && t_xm.Text != "" && t_xb.Text != "" && t_nl.Text != "" && t_books.Text != "" )
{
string myConn1 = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;
OleDbConnection myConn = new OleDbConnection ( myConn1 ) ;
myConn.Open ( ) ;
string strInsert = " INSERT INTO person ( id , xm , xb , nl , zip ) VALUES ( " ;
strInsert += t_id.Text + ", '" ;
strInsert += t_xm.Text + "', '" ;
strInsert += t_xb.Text + "', " ;
strInsert += t_nl.Text + ", " ;
strInsert += t_books.Text + ")" ;
OleDbCommand inst = new OleDbCommand ( strInsert , myConn ) ;
inst.ExecuteNonQuery ( ) ;
myConn.Close ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . BeginEdit ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . EndEdit ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
}
else
{
MessageBox.Show ( "必須填滿所有欄位值!" , "錯誤!" ) ;
}
}
catch ( Exception ed )
{
MessageBox.Show ( "儲存資料記錄發生 " + ed.ToString ( ) , "錯誤!" ) ;
}
}

  同樣對Sql Server 2000資料庫進行插入記錄操作和Access 2000資料庫插入記錄操作的差異也只在於不同的資料連結,具體的代碼可以參考"刪除資料記錄"中的代碼,在這裡就不提供了。
六.Visual C#資料庫編程的完成原始碼和程式啟動並執行主介面:

  掌握了上面要點,編寫一個完整的資料庫編程的程式就顯得非常容易了,下面是Visual C#進行資料庫編程的完整代碼(Data01.cs),此代碼是以Access 2000資料庫為模型設計的,具體如下:

using System ;
using System.Drawing ;
using System.ComponentModel ;
using System.Windows.Forms ;
using System.Data.OleDb ;
using System.Data ;

public class Data : Form
{
private System.ComponentModel.Container components = null ;
private Button lastrec ;
private Button nextrec ;
private Button previousrec ;
private Button firstrec ;
private TextBox t_books ;
private TextBox t_nl ;
private ComboBox t_xb ;
private TextBox t_xm ;
private TextBox t_id ;
private Label l_books ;
private Label l_nl ;
private Label l_xb ;
private Label l_xm ;
private Label l_id ;
private Label label1 ;
private DataSet myDataSet ;
private Button button1 ;
private Button button2 ;
private Button button3 ;
private Button button4 ;
private BindingManagerBase myBind ;

public Data ( )
{
file://串連到一個資料庫
GetConnected ( ) ;
// 對表單中所需要的內容進行初始化
InitializeComponent ( ) ;
}
file://清除在程式中使用過的資源
protected override void Dispose( bool disposing )
{
if( disposing )
{
if ( components != null )
{
components.Dispose ( ) ;
}
}
base.Dispose( disposing ) ;
}
public static void Main ( )
{
Application.Run ( new Data ( ) ) ;
}
public void GetConnected ( )
{
try
{
file://建立一個 OleDbConnection
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM person " ;
file://建立一個 DataSet
myDataSet = new DataSet ( ) ;

myConn.Open ( ) ;
file://用 OleDbDataAdapter 得到一個資料集
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
file://把Dataset綁定books資料表
myCommand.Fill ( myDataSet , "person" ) ;
file://關閉此OleDbConnection
myConn.Close ( ) ;
}
catch ( Exception e )
{
MessageBox.Show ( "串連錯誤! " + e.ToString ( ) , "錯誤" ) ;
}
}
private void InitializeComponent ( )
{

file://添加控制項,略

this.Name = "Data" ;
this.Text = "Visual C#的資料庫編程!" ;
this.ResumeLayout(false) ;
myBind = this.BindingContext [ myDataSet , "person" ] ;
}
protected void New_record ( object sender , System.EventArgs e )
{

t_id.Text = ( myBind.Count + 1 ).ToString ( ) ;
t_xm.Text = "" ;
t_xb.Text = "" ;
t_nl.Text = "" ;
t_books.Text = "" ;

}
protected void Insert_record ( object sender , System.EventArgs e )
{
try
{
file://判斷所有欄位是否添完,添完則執行,反之彈出提示
if ( t_id.Text != "" && t_xm.Text != "" && t_xb.Text != "" && t_nl.Text != "" && t_books.Text != "" )
{
string myConn1 = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;
OleDbConnection myConn = new OleDbConnection ( myConn1 ) ;
myConn.Open ( ) ;
string strInsert = " INSERT INTO person ( id , xm , xb , nl , zip ) VALUES ( " ;
strInsert += t_id.Text + ", '" ;
strInsert += t_xm.Text + "', '" ;
strInsert += t_xb.Text + "', " ;
strInsert += t_nl.Text + ", " ;
strInsert += t_books.Text + ")" ;
OleDbCommand inst = new OleDbCommand ( strInsert , myConn ) ;
inst.ExecuteNonQuery ( ) ;
myConn.Close ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . BeginEdit ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . EndEdit ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
}
else
{
MessageBox.Show ( "必須填滿所有欄位值!" , "錯誤!" ) ;
}
}
catch ( Exception ed )
{
MessageBox.Show ( "儲存資料記錄發生 " + ed.ToString ( ) , "錯誤!" ) ;
}
}

protected void Update_record ( object sender , System.EventArgs e )
{
int i = myBind.Position ;
try{
file://串連到一個資料庫
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb " ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
myConn.Open ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . BeginEdit ( ) ;
file://從資料庫中修改指定記錄
string strUpdt = " UPDATE person SET xm = '"
+ t_xm.Text + "' , xb = '"
+ t_xb.Text + "' , nl = "
+ t_nl.Text + " , zip = "
+ t_books.Text + " WHERE id = " + t_id.Text ;
OleDbCommand myCommand = new OleDbCommand ( strUpdt , myConn ) ;
myCommand.ExecuteNonQuery ( ) ;
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . EndEdit ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
myConn.Close ( ) ;
}
catch ( Exception ed )
{
MessageBox.Show ( "修改指定記錄錯誤: " + ed.ToString ( ) , "錯誤!" ) ;
}
myBind.Position = i ;
}


protected void Delete_record ( object sender , System.EventArgs e )
{
DialogResult r = MessageBox.Show ( "是否刪除目前記錄!" , "刪除目前記錄!" , MessageBoxButtons.YesNo , MessageBoxIcon.Question ) ;
int ss = ( int ) r ;
  if ( ss == 6 ) // 按動"確定"按鈕
{
try{
file://串連到一個資料庫
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb " ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
myConn.Open ( ) ;
string strDele = "DELETE FROM person WHERE id= " + t_id.Text ;
OleDbCommand myCommand = new OleDbCommand ( strDele , myConn ) ;
file://從資料庫中刪除指定記錄
myCommand.ExecuteNonQuery ( ) ;
file://從DataSet中刪除指定記錄
myDataSet.Tables [ "person" ] . Rows [ myBind.Position ] . Delete ( ) ;
myDataSet.Tables [ "person" ] . AcceptChanges ( ) ;
myConn.Close ( ) ;
}
catch ( Exception ed )
{
MessageBox.Show ( "刪除記錄錯誤資訊: " + ed.ToString ( ) , "錯誤!" ) ;
}
}
}

file://按鈕"尾記錄"對象事件程式
protected void GoLast ( object sender , System.EventArgs e )
{
myBind.Position = myBind.Count - 1 ;
}

file://按鈕"下一條"對象事件程式
protected void GoNext ( object sender , System.EventArgs e )
{
if ( myBind.Position == myBind.Count -1 )
MessageBox.Show ( "已經到了最後一條記錄!", "資訊提示!" , MessageBoxButtons.OK , MessageBoxIcon.Information ) ;
else
myBind.Position += 1 ;
}
file://按鈕"上一條"對象事件程式
protected void GoPrevious ( object sender , System.EventArgs e )
{
if ( myBind.Position == 0 )
MessageBox.Show ( "已經到了第一條記錄!" , "資訊提示!" , MessageBoxButtons.OK , MessageBoxIcon.Information ) ;
else
myBind.Position -= 1 ;
}
file://按鈕"首記錄"對象事件程式
protected void GoFirst ( object sender , System.EventArgs e )
{
myBind.Position = 0 ;
}
}

對於以Sql Server 2000資料庫為模型的程式碼,只要把Data01.cs中的資料連結,即:
string myConn1 = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = db.mdb" ;


  改換成:


string strCon = "Provider = SQLOLEDB.1 ; Persist Security Info = False ; User ID = sa ; Initial Catalog = data1 ; Data Source = server1 " ;


  注釋:此資料連結代表的意思是:開啟Sql server資料庫,伺服器名稱為server1,資料庫為data1
就可以得到Visual C#針對Sql Server 2000資料庫為模板編程的完成來源程式代碼了。所以本文就不再提供了。

  七.總結:

  資料庫編程始終是程式編程內容中的一個重點和痛點。而以上介紹的這些操作又是資料庫編程中最為基本,也是最為重要的內容。那些複雜的編程無非是以上這些處理的若干個疊加。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.