關于ADO.NET的書籍和文章很多,在這里主要使用在我教學中給學生做演示的兩個小例子,來比較ADO.NET的連接式和斷開式,程序員一般不喜歡說教,下面就以代碼說話: 連接式: SqlConnection sqlConn=new SqlConnection("server=.;database=pubs;user id=sa;password=;"); SqlCommand sqlComm=new SqlCommand("select * from authors",sqlConn); //操作在打開和斷開數(shù)據(jù)庫之間 sqlConn.Open(); SqlDataReader dr=sqlComm.ExcuteReader(); while(dr.Read()) { for (int i=0; i<dr.FieldCount; i++) { Console.Write(dr.GetValue(i).ToString()+" "); } Console.WriteLine(); } dr.Close(); sqlConn.Close(); 斷開式 SqlConnection sqlConn=new SqlConnection("server=.;database=pubs;user id=sa;password=;"); SqlDataAdapter adapter=new SqlDataAdapter("select * from authors",sqlConn); //用來自動生產更新命令 SqlCommandBuilder cb=new SqlCommandBuilder(adapter); sqlConn.Open(); DataSet ds=new DataSet(); adapter.Fill(ds); sqlConn.Close(); //處理數(shù)據(jù)在打開和關閉之后 for (int i=0; i<ds.Tables[0].Rows.Count; i++) { for (int j=0; j<ds.Tables[0].Columns.Count; j++ { Console.Write(ds.Tables[0].Rows[i][j]+" "); } Console.WriteLine(); } //更改數(shù)據(jù) ds.Tables[0].Rows[0][1]="A"; ds.Tables[0].Rows[1].Delete(); //更新數(shù)據(jù)庫 sqlConn.Open(); adapter.Update(ds); sqlConn.Close();
|