天天看點

ADO.NET五大對象

ADO.NET五大對象

1、Connection:用于連接配接對象,簡單的說就是連接配接資料庫

首先在config配置檔案中配置資料庫連接配接字元串

<connectionStrings>         
<add name="ConnectionString" connectionString="Data Source=.;Initial atalog=XTDB;User ID=sa;Password=123456;"/>
</connectionStrings>
           

在需要使用資料庫的時候先提取配置檔案中的資料庫連接配接 字元串指派給一個變量

public static string cn= ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
           

使用connection對象連接配接資料庫

using (SqlConnection con= new SqlConnection(cn))
            {
                con.open();
                con.close();
            }
           

2、Command:指令對象,執行sql語句,如增删改查

string sql = @"select * from t_student_info";
   SqlCommand cmd=new SqlCommand(sql,connection);
   return cmd.ExecuteNonQuery();
           

ExecuteNonQuery 方法:傳回值為執行sql語句或存儲過程受影響的記錄行數

ExecuteReader:執行CommandText指定的SQL語句或存儲過程名,傳回值類型為DataReader

ExecuteScalar:傳回結果集中的第一行第一列,其傳回值類型為object

3、DataReader:一個向前的隻讀的資料流,以隻進的方式一條一條的讀取資料集中的資料

SqlCommand cmd=new SqlCommand(sql,connection);  
   SqlDataReader dr=cmd.ExecuteReader();  
   while(dr.Read())  
   {  
      fName = (string)dr["FirstName"];
      lName = (string)dr["LastName"]; 
    }  
   cmd.Close();
           

4、DataSet:由資料表的集合構成,相當于記憶體中的資料庫,獨立于各資料源

5、DataAdapter:資料擴充卡,DataAdapter對象相當于資料庫和DataSet之間的橋梁,可以對資料的資料進行增删改查,也可以把從資料庫查詢到的資料通過fill的方式填充到DataSet

SelectCommand屬性:該屬性用來從資料庫中檢索資料。

InsertCommand屬性:該屬性用來向資料庫中插入資料。

DeleteCommand屬性:該屬性用來删除資料庫裡的資料。

UpdateCommand屬性:該屬性用來更新資料庫裡的資料。

SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
//填充,第一個參數是要填充的dataset對象,第二個參數是填充dataset的datatable
Da.Fill(ds);