ASP.NET數(shù)據(jù)庫操作代碼小結(jié):SQL Server篇
ASP.NET數(shù)據(jù)庫操作代碼之DataReader
作用:DataReader閱讀類,執(zhí)行數(shù)據(jù)的“只向前”的讀取。
只讀、只進(jìn)的數(shù)據(jù)流。因?yàn)槊看卧趦?nèi)存中的數(shù)據(jù)只有一行,所以使用DataReader可提高應(yīng)用程序的性能并減少系統(tǒng)開銷。它還提供了未緩沖的數(shù)據(jù)流,該數(shù)據(jù)流使過程邏輯可以有效地按順序處理從數(shù)據(jù)源中返回的結(jié)果。由于數(shù)據(jù)不在內(nèi)存中緩存,所以在檢索大量數(shù)據(jù)時(shí),DataReader是一種合適的選擇。
string strConn="uid=賬號(hào);pwd=密碼;database=數(shù)據(jù)庫;server=服務(wù)器";
SqlConnection ConnSql=new SqlConnection (strConn);
ConnSql.Open ();//打開數(shù)據(jù)庫
string strSQL="SELECT * FROM 表名1";SqlCommand cmd = new SqlCommand(strSQL,ConnSql);SqlDataReader dr=cmd.ExecuteReader();Read();
dr.Close();Close();//關(guān)閉數(shù)據(jù)庫
ASP.NET數(shù)據(jù)庫操作代碼之DataSet
作用:DataSet,DataAdapter讀取數(shù)據(jù)。
string strConn="uid=賬號(hào);pwd=密碼;database=數(shù)據(jù)庫;server=服務(wù)器";
SqlConnection ConnSql=new SqlConnection (strConn);
ConnSql.Open ();string strSQL="SELECT * FROM 表名1 ";
SqlDataAdapter da=new SqlDataAdapter(strSQL,ConnSql); DataSet ds=new DataSet();Fill(ds,"自定義虛擬表名");Close ();//關(guān)閉數(shù)據(jù)庫
ASP.NET數(shù)據(jù)庫操作代碼之ExecuteNonQuery
作用:利用ExecuteNonQuery,執(zhí)行數(shù)據(jù)的插入、更新、刪除。
問:什么是ExecuteNonQuery?
答:在ADO.NET中,ExecuteNonQuery方法用于執(zhí)行不需要返回結(jié)果的命令,如插入、刪除和更新等操作。
string strConn="uid=賬號(hào);pwd=密碼;database=數(shù)據(jù)庫;server=服務(wù)器";
SqlConnection ConnSql=new SqlConnection (strConn);
ConnSql.Open ();string strSQL="INSERT INTO 表名1、UPDATE 表名1 SET、DELETE FROM 表名1";SqlCommand cmd=new SqlCommand (strSQL,ConnSql);ExecuteNonQuery();Close ();//關(guān)閉數(shù)據(jù)庫
ASP.NET數(shù)據(jù)庫操作代碼之ExecuteScalar
作用:利用ExecuteScalar統(tǒng)計(jì)數(shù)據(jù)。
問:什么是ExecuteScalar?
答:ExecuteScalar方法可以返回單個(gè)值,如求和、總行數(shù)等SQL語句的聚合函數(shù)。
string strConn="uid=賬號(hào);pwd=密碼;database=數(shù)據(jù)庫;server=服務(wù)器";
SqlConnection ConnSql=new SqlConnection (strConn);
ConnSql.Open ();//打開數(shù)據(jù)庫
string strSQL="SELECT COUNT(*) FROM 表名1";SqlCommand cmd = new SqlCommand(strSQL,ConnSql);int intNum=(int)cmd.ExecuteScalar();Close();//關(guān)閉數(shù)據(jù)庫
以上就是asp.net與Sql Server數(shù)據(jù)庫操作使用代碼的介紹,希望對大家有所幫助。
【編輯推薦】