歸納總結ADO.NET對象
我們知道做程序就得訪問數據庫,在網上收集了大量的資料,現在和大家分享一下吧。ADO.NET是Microsoft數據庫訪問的一種新技術,它支持連接式訪問和斷開式訪問兩種方案。ADO.NET中定義了一套接口IDbConnection、IDbCommand、IDbDataAdapter和IDDataReader,并且還有顯示這些接口的抽象類:DbConnection、DbCommand、DbDataAdapter以及DataReader;不同的數據庫廠商實現這些接口的抽象類各不相同。
◆ADO.NET對象Connection:Connection對象有兩個屬性:ConnectionString 和 State;以及兩個重要方法:Open和close。
◆ADO.NET對象Command:Command對象有一個屬性:CommandType(sql語句或者存儲過程);三個重要方法:ExecuteNonQuery(增、刪、改影響的行數)、ExecuteReader(返回DataReader對象類型)ExecuteScalar(返回結果集的***行***列值)
◆ADO.NET對象DataReader:DataReader對象不能直接實例化,必須通過Command對象中的一個方法來創建;DataReader有很多屬性,Read(是否還有下一條數據),讀取數據的屬性(三中方式)
◆ADO.NET對象DataAdapter:作用是充當適配器;其中有一個重要方法Fill,這個方法可以在不打開數據庫連接的情況進行數據操作
◆ADO.NET對象DataSet:相當于內存中的一個數據庫,使用DataAdapter對象填充DataSet或者DataTable
◆ADO.NET對象DataTable(DataColumn對象和DataRow對象):它有兩個屬性Columns和Rows;
參數化SQL語句:
Sql2005查詢方法:
- //實例化Connection對象
- SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=AspNetStudy;Persist Security Info=True;User ID=sa;Password=sa");
- //實例化Command對象
- SqlCommand command = new SqlCommand("select * from UserInfo where sex=@sex and age>@age", connection);
- //***種添加查詢參數的例子
- command.Parameters.AddWithValue("@sex", true);
- //第二種添加查詢參數的例子
- SqlParameter parameter = new SqlParameter("@age", SqlDbType.Int);//注意UserInfo表里age字段是int類型的
- parameter.Value = 30;
- command.Parameters.Add(parameter);//添加參數
- //實例化DataAdapter
- SqlDataAdapter adapter = new SqlDataAdapter(command);
- DataTable data = new DataTable();
占位符:
分頁查詢:首先計算出總行數,其次算出多少頁
首先:
- int count = int.Parse(command.ExecuteScalar().ToString());
其次:
- page=(m%n)==0?(m/n):(m/n+1);
n為每頁顯示的行數
***:
- select top 5 * from UserInfo where UserId not in
- (select top (n-1)*5 UserID from UserInfo order by UserID asc)
- order by UserID asc
【編輯推薦】