1. 程式人生 > 實用技巧 >C#使用ADO.NET訪問資料庫

C#使用ADO.NET訪問資料庫

C#使用ADO.NET訪問資料庫

1.常用的資料庫訪問技術

  • 開放式互連技術(ODBC)
  • 物件連結與嵌入式資料庫技術(OLE DB)
  • Java資料庫互連技術(JDBC)
  • ActiveX資料庫物件技術(ADO)
  • ADO.NET技術等

2.認識ADO.NET技術

ado.net是一組用於和資料來源進行互動的面向物件類庫,用於實現使用者到SQL Server等資料來源的連線,為使用者利用SQL語句實現對資料來源中資料的查詢、處理和更新提供支援。

1.ADO.NET的名稱空間及匯入

Microsoft將資料類劃分成不同的名稱空間。在ADO.NET中,主要涉及三個名稱空間:

System.Data
System.Data.SqlClient
System.Data.Oledb

用using 匯入名稱空間,例:

using System.Data;

2.ADO.NET的工作原理及訪問架構

ADO.NET是.NET框架中的資料訪問模型,包含了兩個核心元件:

  • 資料提供程式.NET Framework

    提供程式負責與物理資料來源的連線,用於實現對底層資料來源的訪問

  • 資料集DataSet

    代表實際的資料

ADO.NET的三層資料訪問架構:

各種資料庫/資料來源 <=> .NET資料提供程式 <=> 資料集DataSet

1.各種資料庫/資料來源

是指物理層的資料儲存,可以是SQL Server、Oracle、MySQL、Access等物理資料庫/資料來源。

2…NET資料提供程式

在.NET資料庫應用程式中,使用者通過一個.NET的資料提供者同資料庫互動

Connection 事務:建立與特定資料來源的連線
Command 引數:對資料來源執行操作命令(增刪改查)
DataReader 以順序且只讀的方式從資料來源中讀取資料
DataAdapter 資料介面卡,使用Command物件對資料來源執行SQL命令,將資料從資料庫讀到資料集
* SelectCommand
* InsertCommand  ======填充=====> DataSet
* DeleteCommand
* UpdateCommand

3.資料集DataSet

可把資料集DataSet看成是記憶體中的資料庫,是專門用來處理從資料庫中讀出的資料的。

在從資料庫完成資料查詢後,查詢出的資料就存放在DataSet中,它是從資料來源中查詢到的資料在記憶體中駐留的表示形式,可以把它看成是記憶體中的資料庫。

因此,DataSet是不依賴於資料庫的獨立資料集合,即使斷開資料鏈路,或者關閉資料庫,DateSet依然是可用的。

3.客戶端應用程式基於ADO.NET的兩種資料訪問模式

1.通過DataSet訪問資料(資料集斷開式資料訪問模式)

是指不直接對資料庫進行操作,而是先實現資料庫連線,再通過DataAdapter填充DataSet物件,然後客戶端再通過讀取DataSet來獲取需要的資料。同理,在更新資料庫中的資料時,也是先更新DataSet,然後再通過DataAdapter來更新資料庫中對應的資料。

2.通過DataReader物件訪問資料(連線式資料訪問模式)

是指客戶在操作過程中,與資料庫的連線是開啟的,使用Command物件對資料庫的相關操作,使用DataReader物件以順序方式讀取資料。

3.ADO.NET訪問sql的步驟

1.使用連線物件SqlConnection連線資料來源

// 定義連線字串
string str = "Server=DESKTOP-4HSQLSI\\LRC;database=cs172;integrated security=true";
// string str = "Server=DESKTOP-4HSQLSI\\LRC;database=cs172;uid=登入名;pwd=密碼";
// stirng str = "Data Source=DESKTOP-4HSQLSI\\LRC;Initial Catalog=cs172;integrated security=true";
/**
* Server等同於Data Source 
* database等同於Initial Catalog
* integrated security=true 表示採用信任模式連線(登入資料庫伺服器為window身份驗證)
* uid=登入名;pwd=密碼(登入資料庫伺服器為SQL server身份驗證)
* DESKTOP-4HSQLSI\\LRC 伺服器名稱
* cs172 要連線的資料庫名稱
*/
// 定義資料庫連線物件並初始化
SqlConnection sqlConn = new SqlConnection(str);

2.開啟連線

sqlConn.Open();

3.操作資料庫

  • SqlCommand物件的常用屬性和方法
屬性或方法說明
CommandText 設定或獲取在資料來源上執行的SQL語句或儲存過程名
Connection 設定或返回與Command相關的Connection物件
CreateCommand() 用於建立sqlCommand物件
ExecuteReader() 執行CommandText中的SQL查詢語句,查詢值返回到DataReader物件
ExecuteScalar() 返回單個值,如求和、求最大值等SQL聚合函式
ExecuteNonQuery() 執行增、刪、改等無返回值的SQL操作
  • 增刪改:建立SqlCommand物件,執行SQL語句或儲存過程對資料進行增刪改。

    SqlCommand物件用於通過Connection對資料庫下達操作資料庫的命令

    // 定義SQL語句字串(增刪改)
    string sql = string.Format("delete from cenJi where xueHao='{0}'", xueHao.Text.Trim());
    // 定義資料庫命令物件cmd並初始化
    SqlCommand cmd = new SqlCommand(sql,sqlConn);
    // 執行命令
    cmd.ExecuteNonQuery();
    
  • 查詢:建立SqlCommand物件,執行SQL語句或儲存過程後對返回的“結果”進行操作:

    • 方法一:使用資料讀取器物件DataReader直接一行一行地讀取資料集;

      遍歷DataReader中的記錄

      Command物件在執行ExecuteReader()方法後,在返回記錄的同時,將產生一個數據讀取器物件DataReader來指向所返回的記錄集,利用DataReader就可以讀取返回的記錄。

      DataReader物件用於以最快的速度檢索並檢查查詢所返回的行,返回的記錄是一種只讀的且指標只能前移的資料流

     // 定義一個數據讀取器物件
    SqlDataReader sqlData = command.ExecuteReader();
     //處理資料讀取器sreader中的資料
    // Read()使sqlDataReader移到下一條記錄,SqlDataReader的預設位置在第一條記錄前面
     if (sqlData.Read())
     {
         xinMin.Text = sqlData["xinMin"].ToString();
    	xinBie.Text = sqlData["xinBie"].ToString();
    	senGao.Text = sqlData["senGao"].ToString();
     }
    //關閉DataReader物件
    sqlData.Close();
    
    • DataReader物件的常用屬性和方法
    屬性或方法說明
    FieldCount 當前行中的列數

| Item | DataReader中列的值 |
| HasRows | 指出DataReader是否包含一行或多行 |
| Close() | 關閉DataReader物件 |
| GetName() | 獲取指定列的名稱 |
| GetValue() | 獲取指定序號處的列的值 |
| Read() | 使DataReader移到下一條記錄,返回True表示還有下一條資料,否則表示資料讀取完畢 |

  • 方法二:使用資料集物件DataSet和資料介面卡物件DataAdapter來訪問資料庫。
// sql語句
string sql = "select *from xueSen";
//定義一個數據庫介面卡物件
SqlDataAdapter sda = new SqlDataAdapter(sql, sqlConn);
//定義一個數據集物件
DataSet dataSet = new DataSet();
//將查詢結果填充資料集物件,並用一個表的別名"ds"標記
sda.Fill(dataSet, "ds");
//指定dateGridView的資料來源,dataGridView是以表格方式顯示資料的控制元件
dataGridView1.DataSource = dataSet;
dataGridView1.DataMember = "ds";

​ DataAdapter物件(資料介面卡物件),是DataSet物件與資料來源之間的橋樑,負責從資料來源中檢索資料,並把檢索到的資料填 充到DataSet物件中的表;同時,也把使用者對DataSet物件的更改寫到資料來源中。

​ DataAdapter一般要與DataSet共同使用,來操作資料庫中的資料。

  • DataGridView控制元件的常用屬性
屬性說明
Columns 所有列的集合
Rows 所有行的集合
DataSource 資料來源
DataMember 顯示的表的名稱
RowCount 獲取或設定DataGridview中的顯示行
ReadOnly 是否可編輯單元格
SelectedIndex 獲取選中行的索引
SelectedRow 獲取選中的行

4.關閉連線

//關閉與資料庫的連線
sqlConn.Close();

4.具體示例及完整程式碼

  • 通過vs自帶的window窗體來實現

1.“刪除”按鈕的Click事件程式碼:

private void button1_Click(object sender, EventArgs e)
{
    // 定義連線字串
    string str = "Server=DESKTOP-4HSQLSI\\LRC;database=cs172;integrated security=true";
    // string str = "Server=DESKTOP-4HSQLSI\\LRC;database=cs172;uid=登入名;pwd=密碼";
    // stirng str = "Data Source=DESKTOP-4HSQLSI\\LRC;Initial Catalog=cs172;integrated security=true";
    /**
                 * Server等同於Data Source 
                 * database等同於Initial Catalog
                 * integrated security=true 表示採用信任模式連線(登入資料庫伺服器為window身份驗證)
                 * uid=登入名;pwd=密碼(登入資料庫伺服器為SQL server身份驗證)
                 * DESKTOP-4HSQLSI\\LRC 伺服器名稱
                 * cs172 要連線的資料庫名稱
                 */

    // 定義資料庫連線物件並初始化
    SqlConnection sqlConn = new SqlConnection(str);
    sqlConn.Open();
    try
    {
        // 定義SQL語句字串(增刪改)
        string sql = string.Format("delete from cenJi where xueHao='{0}'", xueHao.Text.Trim());

        // 定義資料庫命令物件cmd並初始化
        SqlCommand cmd = new SqlCommand(sql,sqlConn);

        // 執行命令
        cmd.ExecuteNonQuery();

        MessageBox.Show("刪除成功!", "提示");
    }
    catch(Exception i)
    {
        MessageBox.Show(i.ToString(), "錯誤");
    }
    sqlConn.Close();
}

2.使用SqlCommand物件的ExecuteReader() 方法讀取單行資料。該程式根據使用者指定的學生學號,查詢與該學號對應的學生姓名、性別和身高,並將結果顯示在頁面上

private void Search_Click(object sender, EventArgs e)
{
    string str = "Server = DESKTOP-4HSQLSI\\LRC;database=cs172;integrated security=true";
    SqlConnection sqlConnection = new SqlConnection(str);
    sqlConnection.Open();
    try
    {
        string sql = "select xinMin,xinBie,senGao from xueSen where xueHao='" + xueHao.Text.Trim() + "'";
        // string sql = string.Format("select xinMin,xinBie,senGao from xueSen where xueHao={0}", 						xueHao.Text.Trim());
        SqlCommand command = new SqlCommand(sql, sqlConnection);

        // 定義一個數據讀取器物件
        SqlDataReader sqlData = command.ExecuteReader();

        //處理資料讀取器sreader中的資料
        if (sqlData.Read())
        {
            xinMin.Text = sqlData["xinMin"].ToString();
            xinBie.Text = sqlData["xinBie"].ToString();
            senGao.Text = sqlData["senGao"].ToString();
        }
        else
        {
            MessageBox.Show("該學生不存在!", "提示");
        }

        //關閉DataReader物件
        sqlData.Close();

        sqlConnection.Close();
    }
    catch(Exception i)
    {
        MessageBox.Show(i.ToString(), "錯誤");
    }
}

3.使用SqlDataAdapter和DataSet物件讀取資料。該程式將用表格的形式顯示stu表中全體學生的詳細資訊

private void Form1_Load(object sender, EventArgs e)
{
    string str = "Server = DESKTOP-4HSQLSI\\LRC;database=cs172;integrated security=true";
    SqlConnection sqlConn = new SqlConnection(str);
    sqlConn.Open();

    // sql語句
    string sql = "select *from xueSen";

    //定義一個數據庫介面卡物件
    SqlDataAdapter sda = new SqlDataAdapter(sql, sqlConn);

    //定義一個數據集物件
    DataSet dataSet = new DataSet();

    //將查詢結果填充資料集物件,並用一個表的別名"ds"標記
    sda.Fill(dataSet, "ds");

    //指定dateGridView的資料來源,dataGridView是以表格方式顯示資料的控制元件
    dataGridView1.DataSource = dataSet;
    dataGridView1.DataMember = "ds";

    //關閉與資料庫的連線
    sqlConn.Close();
}

, sqlConn);

//定義一個數據集物件
DataSet dataSet = new DataSet();

//將查詢結果填充資料集物件,並用一個表的別名"ds"標記
sda.Fill(dataSet, "ds");

//指定dateGridView的資料來源,dataGridView是以表格方式顯示資料的控制元件
dataGridView1.DataSource = dataSet;
dataGridView1.DataMember = "ds";

//關閉與資料庫的連線
sqlConn.Close();

}