ADO.NET | 使用Command對象操作數據庫


零、友情鏈接


一、常用屬性及說明

在使用connection對象鏈接到數據庫之後,就可以使用Command對象對數據庫進行增刪改查了,操作實現的方式使用的是SQL語句。Command對象可以分爲四個不同的執行命令對象,分別是:SqlCommandOledeCommandOdbcCommdOracleCommand,這幾個對象的常用的屬性以及方法幾乎相同,但是最配套asp.net使用的是SqlCommand,下面是SqlCommand對象常用屬性以及說明:

屬性 說明
CommandType 獲取或設置SqlCommand對象要執行命令的類型
CommandText 獲取或設置要對數據源執行的SQL語句、存儲過程或表名
CommandTimeOut 獲取或設置在終止對執行命令的嘗試並生成錯誤之前的等待時間
Connection 獲取或設置SqlCommand對象所使用的Connection對象的名稱
Parameters 獲取SqlCommand對象需要使用的參數集合

常用方法:

方法 說明
ExecuteNonQuery 對連接執行的SQL語句並返回受執行的行數
ExecuteReader 對連接執行SQL語句並返回保持連接的數據讀取器對象SqlDataReader
ExecuteScalar 執行查詢,並返回查詢結果集中的第1行的第1列的值

二、查詢數據指令

通過查詢語句或調用存儲過程將數據庫中的數據檢索出來,通過指定的接收方法來得到這些數據。

查詢的結果可能是一行一列,也可能是多行多列

例子:查詢數據庫中的數據

先來看一下效果,這個圖片是從數據庫中讀取出來然後利用Response.write寫在頁面上的:
在這裏插入圖片描述
ok,開始寫代碼,首先打開安裝好的SQL Server 2014 Management Studio,連接好之後,點擊新建查詢,輸入以下SQL語句,創建一個表:

Create Database School
go
use School
go
create table Student
(
	ID int primary key identity(1,1),
	Name varchar(60),
	Sex char(2),
	Age int,
	Class varchar(60)
)

寫完這些之後,表就創建好了,接着手動輸入一些數據:
在這裏插入圖片描述
然後打開VS,創建一個WEB窗體,再新建一個Default.aspx作爲首頁,打開Default.aspx,cs開始寫代碼:

首先引用需要使用的命名空間:

using System.Data;
using System.Data.SqlClient;
using System.Data.Text;

頁面加載Load方法

protected void Page_Load(object sender, EventArgs e)
{
	string Result = GetSqlData();
    Response.Write(Result);
}

定義GetSqlData方法,實現SqlCommand對象執行SQL查詢命令並返回數據:

private string GetSqlData()
{
    StringBuilder res = new StringBuilder();
    res.Append("<table>");           //手動創建表格列表並將字符串追加到StringBuilder類
    //定義表格頭部
    res.Append("<tr><th>序號</th><th>姓名</th><th>性別</th><th>年齡</th><th>班級</th></tr>");
    //使用using指令創建SqlConnection對象
    using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();     //實例化一個執行數據庫操作的命令類
        comm.CommandType = CommandType.Text;   //指定要執行數據庫操作的的命令是SQL語句
        comm.CommandText = "select * from Student";         //要查詢的SQL語句
        comm.Connection = conn;     //指定需要的數據庫連接類
        //執行數據庫查詢並返回SqlDataReader類型數據接收器
        using(SqlDataReader DataReader = comm.ExecuteReader())
        {
            //使用數據接收器執行數據行的循環讀取
            while (DataReader.Read())
            {
                int ID = (int)DataReader["ID"];
                string Name = (string)DataReader["Name"];
                string Sex = (string)DataReader["Sex"];
                int Age = (int)DataReader["Age"];
                string Class = (string)DataReader["Class"];
                //開始連接
                res.Append("<tr><td>" + ID + "</td>");
                res.Append("<td>" + Name + "</td>");
                res.Append("<td>" + Sex + "</td>");
                res.Append("<td>" + Age + "</td>");
                res.Append("<td>" + Class + "</td></tr>");
            }
        }
        conn.Dispose();     //數據庫釋放
    }
    res.Append("</table>");
    return res.ToString();
}

在以上代碼中,利用了StringBuilderAppend方法,在定義的串中,加入了HTML元素,直接在頁面中生成表格,在打開頁面之後,檢查一下頁面元素:
在這裏插入圖片描述
可以很清楚的看到,StringBuilder已經幫我們寫入表格的元素了。,最後用CSS代碼對錶格進行一下美化:

<style type="text/css">
    /*設置表格、表頭、單元格的邊框及顏色和樣式*/
    table,table th,table td{
        border:1px;
        border-style:solid;
        border-color:#22bbad;
    }
    /*重寫表頭的邊框顏色*/
    table th{
        border-color:white;
    }
    /*將表格中的邊框合併*/
    table{
        border-collapse:collapse;
    }
    /*設置表頭的大小及顏色*/
    table th{
        width:150px;
        height:30px;
        text-align:center;
        background-color:#22bbad;
        color:white;
    }
    /*設置單元格的高度與文本位置*/
    table td{
        height:30px;
        text-align:center;
    }
</style>

大功告成!!!

暫時不要刪除這個代碼!這個代碼貫穿整個博客!!


三、添加數據指令

同樣使用SqlCommand對象進行添加,添加記錄不需要考慮選擇用哪種方式接收。

使用ExecuteNonQuery方法執行插入數據時,所接收的結果也是被影響的行數。

下面是執行插入的語句:

comm.CommandText = "insert into Student([Name],[Sex],[Age],[Class]) values('" + Name + "','" + Sex + "','" + Age + "','" + Class +"')";

例子:基於上一個例子,進行添加數據操作

首先用表單設計好呈現在網頁上的添加效果:

<form id="form1" runat="server">
    <div>
    </div>
    <div>
        <br /><hr />
        <table class="addtab" align="center">
            <tr><td width="60">姓名:</td>
                <td>
                    <asp:TextBox ID="Txt_Name" runat="server"></asp:TextBox></td>
            </tr>
            <tr><td>性別:</td>
                <td>
                    <asp:DropDownList ID="DDL_Sex" runat="server">
                        <asp:ListItem Text="男" Value="男"></asp:ListItem>
                        <asp:ListItem Text="女" Value="女"></asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr><td>年齡:</td>
                <td><asp:TextBox ID="Txt_Age" runat="server"></asp:TextBox></td>
            </tr>
            <tr><td>班級</td>
                <td>
                    <asp:TextBox ID="Txt_Class" runat="server"></asp:TextBox></td>
            </tr>
            <tr><td colspan="2">
                <asp:Button ID="Btn_Add" runat="server" Text="添加" OnClick="Btn_Add_Click" /></td></tr>
        </table>
    </div>
</form>

設計出來是這樣的:
在這裏插入圖片描述
緊接着,給添加Button按鈕加一個Click事件:

protected void Btn_Add_Click(object sender, EventArgs e)
{
    string Name = this.Txt_Name.Text.ToString().Trim();
    string Sex = this.DDL_Sex.SelectedValue;
    string Age = this.Txt_Age.Text.ToString().Trim();
    string Class = this.Txt_Class.Text.ToString().Trim();
    //這裏爲什麼使用using,因爲使用using可以自動釋放新建的對象
    using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();     //實例化執行數據庫操作的命令類
        comm.CommandType = CommandType.Text;    //指定發送到數據庫的執行命令爲Sql語句
        //定義插入數據庫的SQL語句
        comm.CommandText = "insert into Student([Name],[Sex],[Age],[Class]) values ('" + Name + "','" + Sex + "','" + Age + "','" + Class + "')";
        comm.Connection = conn;     //指定SqlCommand類所需要的數據庫連接類
        int AddRows = comm.ExecuteNonQuery();
        conn.Dispose();
        if (AddRows > 0)
        {
            Response.Redirect("Default.aspx");
        }
    }
}

注意:sql語句中後面的 values 每項需要加單引號 '

看一下效果:

在這裏插入圖片描述
這時候添加數據已經能成功,但是在實際運行的時候會產生多餘的數據讀取過程,並且在單擊添加按鈕時發生了頁面回發,所以需要添加IsPostBack來驗證回發:

if (!IsPostBack)
{
	string Result = GetSqlData();
	Response.Write(Result);
}

四、修改數據指令

修改數據指令的實現方式與插入數據相同,但編寫的SQL語句不同,同樣,修改成功後SqlCommand將會得到所影響的行數。

例子:實現數據的修改

先簡單說一下這個例子的思路:

在原來的表單後面新增一個編輯列,點擊這個編輯就會重定向到一個新建的EditData.aspx頁面,並且傳送一個ID參數。新建的EditData頁面只包含修改的內容,爲了讓之前表單裏面的內容顯示到新頁的控件上,在EditData.aspx.cs中定義一個GetData方法綁定值,緊接着修改完控件上的值了再添加到數據庫中,重定向到最開始的頁面。

Default.aspx.cs頁面增加編輯單列:

res.Append("<tr><th>序號</th><th>姓名</th><th>性別</th><th>年齡</th><th>班級</th><th>操作</th></tr>");
……省略,大部分和上面的相似
res.Append("<td><a href=\"EditData.aspx?ID=" + ID + "\">編輯</a></td></tr>");

EditData.aspx頁面新建一個像添加選項一樣的表單,只是多了一個HiddenField隱藏域存儲傳過來的ID

/*這句話在EditData.aspx 的 < / table>之下*/
<asp:HiddenField ID="EditID" runat="server" />

EditData.aspx.csGetData方法:

private void GetData(string ID)
{
    using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();
        comm.CommandType = CommandType.Text;
        //定義查詢語句
        comm.CommandText = "select Name,Sex,Age,Class from Student where ID=" + ID;
        comm.Connection = conn;
        using(SqlDataReader datareader = comm.ExecuteReader())
        {
            datareader.Read();
            string Name = (string)datareader["Name"];
            int Age = (int)datareader["Age"];
            string Class = (string)datareader["Class"];
            string Sex = (string)datareader["Sex"];
            //綁定到控件上
            this.Txt_Name.Text = Name;
            this.Txt_Age.Text = Age.ToString();
            this.Txt_Class.Text = Class;
            foreach(ListItem item in this.DDL_Sex.Items)
            {
                if (item.Value == Sex)
                {
                    item.Selected = true;
                    break;
                }
            }
        }
        comm.Dispose();
    }
}

EditData.aspx.cs中按鈕的點擊方法:

protected void Btn_Edit_Click(object sender, EventArgs e)
{
    string ID = this.EditID.Value;
    string Name = this.Txt_Name.Text.Trim();
    string Age = this.Txt_Age.Text.Trim();
    string Sex = this.DDL_Sex.SelectedValue;
    string Class = this.Txt_Class.Text.Trim();
    using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();
        comm.CommandType = CommandType.Text;
        comm.CommandText = "update Student set Name='" + Name + "',Sex='" + Sex + "',Age='" + Age + "',Class='" + Class + "' where ID=" + ID;
        comm.Connection = conn;
        int AddRows = comm.ExecuteNonQuery();
        if (AddRows > 0)
        {
            Response.Redirect("Default.aspx");
        }
    }
}

另外,在EditData.aspx.csPage_Load方法中,判斷一下是否回發,並且把傳過來的ID賦值給隱藏域,最後執行GetData方法。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string ID = Request.QueryString["ID"];
        //將值綁定到隱藏域控件上
        this.EditID.Value = ID;
        GetData(ID);
    }
}

大功告成,效果如下:
在這裏插入圖片描述

五、刪除數據指令

刪除數據與前面的實現過程相同,編寫一條刪除SQL語句即可通過SqlCommand對象進行刪除操作,當數據刪除成功後同樣會接收到所影響的行數。

例子:刪除操作

同樣的,在原有表單後面增加一個列名字是刪除操作,只要點擊這個刪除就轉向一個新頁,刪除完之後再重定向到起始頁。

新頁DeleteData.aspx.csPage_Load 代碼:

string ID = Request.QueryString["ID"];
DelData(ID);

DeletData.aspx.cs中的DelData方法:

private void DelData(string ID)
{
    using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();
        comm.CommandType = CommandType.Text;
        comm.CommandText = "delete Student where ID=" + ID;
        comm.Connection = conn;
        int DelCount = comm.ExecuteNonQuery();
        if (DelCount > 0)
        {
            Response.Redirect("Default.aspx");
        }
        comm.Dispose();
    }
}

完成!

整個最後的效果展示

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章