ADO.NET的學習

來源:互聯網
上載者:User

標籤:dir   lan   fill   res   arc   cmdb   add   strong   rect   

 ADO.NET的幾個對象
  • Connection:管理資料庫的串連
  • Command:對資料庫執行命令
  • DataReader:資料流讀取器,返回的資料都是快速的且只是“向前”的資料流。無法執行個體化,只能通過Command建立
  • DateSet:快取資料,對資料進行操作
  • DataAdapter:資料配接器,資料庫和DataSet的橋樑
ADO.NET命名空間

 註:圖取自網路

常見的是SQL資料來源

引用命名空間:

using System.Data.SqlClient;
一、Connection類

串連資料庫,Connection會被Command對象使用,這樣就能夠知道是在哪個資料來源上面執行命令。

Connection有兩個重要屬性:ConnectionString和State,連接字串和串連狀態

       兩個重要方法:Open()和Close(),用來開啟和關閉資料庫連接

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {            conn.Open();       }

 conn.State.ToString():當前串連狀態,傳回值為Closed 或Open

二、Command對象

Command有兩個重要屬性:CommandType, 指明CommandText 是SQL語句,預存程序還是表操作,預設值為CommandType.Text; 

                                                    兩個值:(1)CommandType.StoredProcedure,以預存程序方式執行

                           (2)CommandType.Text SQL語句執行

                           (3)CommandType.TableDirect,直接處理某個表

               CommandText,值為SQL語句或是預存程序名詞,預設為SQL語句

建立命令對象的兩種方式

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {            conn.Open();       SqlCommand SqlCommand= conn .CreateCommand(); //這種方式比較好
SqlCommand.CommandText="select * from Student"; //或是執行個體化一個對象 //SqlCommand sqlcmd=new SqlCommand(); //sqlcmd.CommandText ="select * from student"; //sqlcmd.Connection=conn;
}

 

三個重要方法:

  • ExecuteReader():返回DataReader對象,DataReader對象說明詳見下文

 

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {             SqlCommand command = conn.CreateCommand();   command.CommandText = "Select * form Student";
   //CommandBehavior.CloseConnetion 關閉dataReader時,同時也把與它相關聯的Connection串連也一起關閉   
using (SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection))   {    while (dr.Read())     {      //開始讀取資料了,接下來你想怎麼樣就怎麼樣了      string str = dr.GetSqlString(0).ToString();    }  } }

 

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {            SqlConnection conn = new SqlConnection(str);        //建立串連    SqlCommand cmd = conn.CreateCommand();              //建立命令    cmd.CommandText = "SELECT * FROM Person";           //設定作業語句    conn.Open();                                        //開啟串連    //SqlDataReader讀取資料    using (SqlDataReader reader = cmd.ExecuteReader())    {      while (reader.Read())        {               Console.WriteLine(reader[0] + ":" + reader[1]);  //輸出當前行的第一列,第二列資料        }    }    cmd.CommandText = "SELECT Count(*) FROM Person";    object obj = cmd.ExecuteScalar();                   //僅查詢第一行第一列    Console.WriteLine((int)obj); conn.Close();  //關閉串連 }
  • ExecuteScalar():返回資料第一行第一列的值,如Count(*),如果沒有資料,則返回NULL
  • ExecuteNonQuery():返回增、刪、改的影響行數
using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {             SqlCommand cmd = conn.CreateCommand();              //建立命令    cmd.CommandText = "Update Person Set PersonName = ‘Ado.net修改‘ WHERE PersonId = @Id";    //設定作業語句    cmd.Parameters.Add("@Id", SqlDbType.Int);           //添加參數,說明類型    cmd.Parameters["@Id"].Value = 1;                    //設定參數值    conn.Open();                                        //開啟串連    int i = cmd.ExecuteNonQuery();                      //執行命令,ExecuteNonQuery由名稱看出,只能用於非查詢語句    conn.Close();                                       //關閉串連    Console.WriteLine(i);                               //輸出影響行數

  //直接使用參數集合添加你需要的參數,推薦這種寫法
  //SqlParameter[] parameters = new SqlParameter[]
  //{
    //new SqlParameter("@name",SqlDbType.NVarChar,100){Value = "yang"},
    //new SqlParameter("@age",SqlDbType.Int,2){Value = 888},
    //new SqlParameter("@address",SqlDbType.NVarChar,20){Value = "Jiang Su"}, 
  //};
  //ommand.Parameters.AddRange(parameters);
}
 三、DataReader類

常見方法:

(1)Read()返回Bool,是否還有下一行,並移到結果集的下一行

(2)GetOrdinal(string 列名),返回序號,通過列名來擷取當前列的索引號,這樣如果下次你列名順序發生變化也沒有關係

(3)GetName(int 序號):  擷取列名,參數為指定列名的序號,返回string

int nameId= dr.GetOrdinal("name");string columnName = dr.GetName(nameId);
//知道列名擷取值
using (SqlDataReader reader = cmd.ExecuteReader())
{   while (reader.Read())     {        Console.WriteLine(reader.GetString(sdr.GetOrdinal("name"))); 
   } 
}

(4)NextResult(),當查詢為批處理查詢時,使用這個方法去讀取下一個結果集,傳回值為Bool,如果存在多個結果集,則為 true;否則為 false

using (SqlConnection conn = new SqlConnection(strConnString))
{   conn.Open();  
using (SqlCommand cmd = new SqlCommand())
   {     cmd.Connection
= conn;     // 利用分號「;」串聯多句 SQL 陳述式,之後再一次丟進資料庫去執行,達成「批次」讀取或更新     // 資料庫的目的。此技巧亦適用於 INSERT、UPDATE、DELETE 的「批次」執行。      cmd.CommandText = "SELECT 欄位1,欄位2 FROM 資料表1 ; SELECT * FROM 資料表2";     using (SqlDataReader dr = cmd.ExecuteReader())
     {      
while(dr.Read())
       {         
this.DropDownList1.Items.Add(dr.GetSqlString(0).ToString() + dr.GetSqlInt32(1).ToString());       }     dr.NextResult();      while(dr.Read())
    {         
this.DropDownList2.Items.Add(dr.GetString(0) + dr.GetInt32(1));      }    }  }}

 

四、SqlDataAdapter 資料配接器

有四個重載

無參SqlDataAdapter(SqlCommand)          // 執行命令對象執行個體SqlDataAdapter(String, SqlConnection)   //只能指定查詢語句 ②連線物件執行個體SqlDataAdapter(String, ConnectionString)// 用 SelectCommand 和一個連接字串初始化 SqlDataAdapter 類的一個新執行個體

一個重要方法:Fill(),資料填充至DataSet

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {        DataSet dataSet = new DataSet();      conn.Open();    SqlCommand command = conn.CreateCommand();    command.CommandText = "select name,age,address from MyInformation";    SqlDataAdapter dataAdapter = new SqlDataAdapter(command);    dataAdapter.Fill(dataSet);  //填充資料}

對資料進行增加操作

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {            using (SqlConnection conn = new SqlConnection(ConnectionString())) {     conn.Open();     //構建查詢語句,也可以指定SqlCommand,其中變換的方法有很多     SqlDataAdapter da = new SqlDataAdapter("select LastName,FirstName from dbo.Employees", conn);     DataSet ds = new DataSet();     da.Fill(ds);     //這句話很重要,它會把你在DataSet增加的資料轉化為SQL語句用來更新資料庫     SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);     //添加行,執行個體化一個行對象,注意是用NewRow來建立行     DataRow row = ds.Tables[0].NewRow();     row[0] = "Yang";     row[1] = "鬼頭";     ds.Tables[0].Rows.Add(row);  //添加到表中     da.Update(ds);             //把DataSet中表和資料庫進行對比,更新 }     }

更新操作

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {            using (SqlConnection conn = new SqlConnection("")){    SqlDataAdapter da = new SqlDataAdapter("SQL語句或你自己定義的命令對象", conn);    DataSet ds = new DataSet();    da.Fill(ds);    //很重要的一句話    SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);    ds.Tables[0].Rows[12][1] = ""; //修改資料    da.Update(ds);    //調用Update方法其中隱式的調用了AcceptChanges方法,更新資料集中的資料    //如果你繼續使用這個資料集而沒有調用這個方法,在後面的使用會出現異常    ds.AcceptChanges();  //這句話可以不寫的}  }
最後

對於一些增刪改,都應加上事務,防止出錯能復原資料

using (SqlConnection conn = newSqlConnection("DataSource(local);Integrated Security=SSPI;Initial Catalog=Northwind"))    {    //事務     SqlTransaction myTran = con.BeginTransaction();     tyr   {        //正常代碼執行           ..............
//提交事務 myTran.Commit(); }
catch(Exception e) { //出錯,交易回復 myTran.Rollback(); } }

 

ADO.NET的學習

聯繫我們

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