ASP.NET之SqlDataSource控件簡單增刪查改

數據庫連接

從工具箱中把SqlDataSource控件拖放到頁面aspx中。

在這裏插入圖片描述

點擊配置數據源可以選擇連接目標。默認是沒有選項的,我們點擊新建連接,然後從身份驗證中選擇想連接的服務器是默認的windows身份驗證還是sql server驗證,我這裏是windows身份驗證,它的服務器名是一個點(.)然後選擇數據庫,最後測試下連接即可確定。

在這裏插入圖片描述

隨即我們會發現從web.config文件中看到多了些代碼:

<connectionStrings>
    <add name="studentsConnectionString" connectionString="Data Source=.;Initial Catalog=students;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>

這些就是公共的數據庫連接配置。

connectionStrings節點兩種方式:

<connectionStrings> 
第一種:
<add name="名稱" connectionString="Data Source=服務器名;Initial Catalog=數據庫名;User ID=用戶;Password=密碼" providerName="System.Data.SqlClient" />
第二種:
<add name="名稱" connectionString="server=服務器名;database=數據庫名; Ueer ID=用戶;Password=密碼" providerName="System.Data.SqlClient" />
</connectionStrings> 
在頁面還可以這樣引用<%$ ConnectionString:Name%>.

接下來看回aspx文件:

<%--數據庫配置--%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>" >
</asp:SqlDataSource>

很明顯它幫我們引入了web.config文件中的ConnectionString配置對象。

至此,數據庫連接操作完成。

查詢

查詢之前,我們需要把查詢的命令給它加上去。所以,我們可以在SqlDataSource控件中綁定查詢命令SelectCommand屬性。

<%--數據庫配置--%>
<asp:SqlDataSource 
    ID="SqlDataSource1" 
    runat="server" 
    ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>" 
    SelectCommand="SELECT * FROM [Table1]">
</asp:SqlDataSource>

然後我們從工具箱中拖動一個GridView控件進行查看數據庫表,GridView可以綁定SqlDataSource控件得到查詢信息。

<%--查詢--%>
<h1>查詢數據</h1>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
        <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
    </Columns>
</asp:GridView>

從上方能看到,DataSourceID屬性能夠綁定SqlDataSource控件的ID(SqlDataSource1),然後在控件中手寫入Columns控件,可以裝載其他控件,我們再拖入BoundField控件,讓其綁定id,name進行渲染操作,這裏就相當於一個for循環操作了,注意:綁定的id,name屬性都是表字段名稱。

再運行程序打開瀏覽器就看到查詢數據了。

插入

插入之前,我們給SqlDataSource控件寫上插入命令,values值我們可以綁定成傳入的形參形式表示(@id,@name)。

<%--數據庫配置--%>
<asp:SqlDataSource 
    ID="SqlDataSource1" 
    runat="server" 
    ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>" 
    SelectCommand="SELECT * FROM [Table1]" 
    InsertCommand="insert into [Table1] values(@id,@name);">
</asp:SqlDataSource>

我們拖動一些新的表單進行插入操作。

<%--插入--%>
<h1>插入數據</h1>
<asp:Label ID="Label2" runat="server" Text="學號:"></asp:Label>
<asp:TextBox ID="StuId" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="姓名:"></asp:Label>
<asp:TextBox ID="StuName" runat="server"></asp:TextBox>
<br />
<asp:Button ID="AddButton" runat="server" Text="添加" OnClick="AddButton_Click1"/><br />
<asp:Label ID="AddMsg" runat="server" Text=""></asp:Label>

新數據輸入完畢之後點擊按鈕執行AddButton_Click1插入事件。於是我們開始從CS文件中寫邏輯了。

protected void AddButton_Click1(object sender, EventArgs e)
{
    //獲取表單數據
    string id = StuId.Text;
    string name = StuName.Text;

    //執行插入
    SqlDataSource1.InsertParameters.Add("id", id);
    SqlDataSource1.InsertParameters.Add("name", name);

    //SqlDataSource1.Insert() 返回影響行數大於0則
    if (SqlDataSource1.Insert() > 0)
    {
        AddMsg.Text = "數據添加成功";
        
        //刷新頁面(重定向)
        Response.Redirect("/WebForm1.aspx");
        return;
    }
    AddMsg.Text = "數據添加失敗";
}

修改

修改之前,我們給SqlDataSource控件寫上修改命令,values值我們可以綁定成傳入的形參形式表示。

<%--數據庫配置--%>
<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>"
    SelectCommand="SELECT * FROM [Table1]"
    InsertCommand="insert into [Table1] values(@id,@name);"
    UpdateCommand="update [Table1] set name=@name where id=@id;">
</asp:SqlDataSource>

同理,添加表單做修改操作。

<%--修改--%>
<h1>修改數據</h1>
<br />
<asp:Label ID="Label6" runat="server" Text="學號:"></asp:Label>
<asp:TextBox ID="StuId2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label7" runat="server" Text="姓名:"></asp:Label>
<asp:TextBox ID="StuName2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateButton_Click"/>
<asp:Label ID="UpdateMsg" runat="server"></asp:Label>

CS文件中寫UpdateButton_Click修改事件。

protected void UpdateButton_Click(object sender, EventArgs e)
{
    string id = StuId2.Text;
    string name = StuName2.Text;

    if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name) )
    {
        UpdateMsg.Text = "數據項不能爲空";
        return;
    }

    SqlDataSource1.UpdateParameters.Add("id", id);
    SqlDataSource1.UpdateParameters.Add("name", name);

    if (SqlDataSource1.Update() > 0)
    {
        UpdateMsg.Text = "數據更新成功";
        Response.Redirect("/WebForm1.aspx");
        return;
    }
    UpdateMsg.Text = "數據更新失敗";
}

刪除

刪除之前,我們給SqlDataSource控件寫上刪除命令,values值我們可以綁定成傳入的形參形式表示。

<%--數據庫配置--%>
<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>"
    SelectCommand="SELECT * FROM [Table1]"
    InsertCommand="insert into [Table1] values(@id,@name);"
    UpdateCommand="update [Table1] set name=@name where id=@id;"
    DeleteCommand="delete from [Table1] where id=@id;">
</asp:SqlDataSource>

我們增加一個表單來獲取用戶即將要刪除的ID號。

<%--刪除--%>
<h1>刪除數據</h1>
<br />
<asp:Label ID="Label10" runat="server" Text="學號:"></asp:Label>
<asp:TextBox ID="StuId3" runat="server"></asp:TextBox>
<br />
<asp:Button ID="DeleteButton" runat="server" Text="刪除" style="width: 40px"  OnClick="DeleteButton_Click" />
<asp:Label ID="DeleteMsg" runat="server"></asp:Label>

CS文件中寫DeleteButton_Click刪除事件。

protected void DeleteButton_Click(object sender, EventArgs e)
{
    string id = StuId3.Text;
    if (String.IsNullOrEmpty(id))
    {
        DeleteMsg.Text = "數據項不能爲空";
        return;
    }
    SqlDataSource1.DeleteParameters.Add("id", id);
    if (SqlDataSource1.Delete() > 0)
    {
        DeleteMsg.Text = "數據刪除成功";
        Response.Redirect("/WebForm1.aspx");
        return;
    }
    DeleteMsg.Text = "數據刪除失敗";
}

全部代碼

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="dataDemo.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

        <%--數據庫配置--%>
        <asp:SqlDataSource
            ID="SqlDataSource1"
            runat="server"
            ConnectionString="<%$ ConnectionStrings:studentsConnectionString %>"
            SelectCommand="SELECT * FROM [Table1]"
            InsertCommand="insert into [Table1] values(@id,@name);"
            DeleteCommand="delete from [Table1] where id=@id;"
            UpdateCommand="update [Table1] set name=@name where id=@id;">
        </asp:SqlDataSource>

        <%--查詢--%>
        <h1>查詢數據</h1>
        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <br />
        <br />

        <%--插入--%>
        <h1>插入數據</h1>
        <asp:Label ID="Label2" runat="server" Text="學號:"></asp:Label>
        <asp:TextBox ID="StuId" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label3" runat="server" Text="姓名:"></asp:Label>
        <asp:TextBox ID="StuName" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="AddButton" runat="server" Text="添加" OnClick="AddButton_Click1"/><br />
        <asp:Label ID="AddMsg" runat="server" Text=""></asp:Label>
        <br />
        <br />

        <%--修改--%>
        <h1>修改數據</h1>
        <br />
        <asp:Label ID="Label6" runat="server" Text="學號:"></asp:Label>
        <asp:TextBox ID="StuId2" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label7" runat="server" Text="姓名:"></asp:Label>
        <asp:TextBox ID="StuName2" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="UpdateButton" runat="server" Text="更新"
            OnClick="UpdateButton_Click"/>
        <asp:Label ID="UpdateMsg" runat="server"></asp:Label>
        <br />
        <br />


        <%--刪除--%>
        <h1>刪除數據</h1>
        <br />
        <asp:Label ID="Label10" runat="server" Text="學號:"></asp:Label>
        <asp:TextBox ID="StuId3" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="DeleteButton" runat="server" Text="刪除"
             style="width: 40px" OnClick="DeleteButton_Click"
         />
        <asp:Label ID="DeleteMsg" runat="server"></asp:Label>
        <br />
        <br />


    </form>
</body>
</html>

cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace dataDemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void AddButton_Click1(object sender, EventArgs e)
        {
            string id = StuId.Text;
            string name = StuName.Text;

            SqlDataSource1.InsertParameters.Add("id", id);
            SqlDataSource1.InsertParameters.Add("name", name);

            if (SqlDataSource1.Insert() > 0)
            {
                AddMsg.Text = "數據添加成功";
                Response.Redirect("/WebForm1.aspx");
                return;
            }
            AddMsg.Text = "數據添加失敗";
        }
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            string id = StuId2.Text;
            string name = StuName2.Text;

            if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name) )
            {
                UpdateMsg.Text = "數據項不能爲空";
                return;
            }

            SqlDataSource1.UpdateParameters.Add("id", id);
            SqlDataSource1.UpdateParameters.Add("name", name);

            if (SqlDataSource1.Update() > 0)
            {
                UpdateMsg.Text = "數據更新成功";
                Response.Redirect("/WebForm1.aspx");
                return;
            }
            UpdateMsg.Text = "數據更新失敗";
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            string id = StuId3.Text;
            if (String.IsNullOrEmpty(id))
            {
                DeleteMsg.Text = "數據項不能爲空";
                return;
            }
            SqlDataSource1.DeleteParameters.Add("id", id);
            if (SqlDataSource1.Delete() > 0)
            {
                DeleteMsg.Text = "數據刪除成功";
                Response.Redirect("/WebForm1.aspx");
                return;
            }
            DeleteMsg.Text = "數據刪除失敗";
        }

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