溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET如何連接數(shù)據(jù)庫

發(fā)布時(shí)間:2021-09-17 09:14:55 來源:億速云 閱讀:144 作者:小新 欄目:編程語言

這篇文章主要介紹了ASP.NET如何連接數(shù)據(jù)庫,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

數(shù)據(jù)庫連接篇

在WEB項(xiàng)目里看到Web.config配置文件,在configuration這行加入下面代碼用于和SQL服務(wù)器進(jìn)行連接

<appSettings>
<!-- 數(shù)據(jù)庫連接字符串 -->
<add key="ConnStr" value="Data Source=localhost;database=company;UID=sa;Password=;Persist Security Info=True;" />
</appSettings>

數(shù)據(jù)列表顯示篇,如圖:

ASP.NET如何連接數(shù)據(jù)庫

using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//引用命名空間:SQL托管,配置文件
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{
    protected SqlConnection myconn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    //讀取web.config配置文件中的數(shù)據(jù)庫連接字符串,并連接到指定的數(shù)據(jù)庫
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)//判斷頁面是否第一次運(yùn)行
     {
          string strsql="select * from Product";//定義一個數(shù)據(jù)庫的查詢字符串
                DataSet ds = new DataSet();
                myconn.Open();//打開數(shù)據(jù)庫連接
                SqlDataAdapter command = new SqlDataAdapter(strsql,myconn);//表示用于填充DataSet 和更新SQL Server 數(shù)據(jù)庫的一組數(shù)據(jù)命令和一個數(shù)據(jù)庫連接 
                command.Fill(ds, "Product");
                productList.DataSource = ds.Tables[0].DefaultView;
                productList.DataBind();
                ds.Clear();
          myconn.Close();//關(guān)閉數(shù)據(jù)庫連接
            }
 }
    protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        foreach (System.Web.UI.WebControls.HyperLink link in e.Item.Cells[7].Controls)
        {
            link.Attributes.Add("onClick", "if (!window.confirm('您真的要刪除這條記錄嗎?')){return false;}");
        }
    }
}

數(shù)據(jù)添加篇

protected void btnAdd_Click(object sender, EventArgs e)
    {
        string ProductId = this.txtProductId.Text;
        string CategoryId = this.txtCategoryId.Text;
        string Name = this.txtName.Text;
        string Description = this.txtDescription.Text;
        string Price =this.txtPrice.Text;
        string sql_Exeits = "select * from Product where ProductId='" + ProductId + "'";
        SqlCommand cmd_Exeits = new SqlCommand(sql_Exeits, myconn);
        myconn.Open();
        SqlDataReader rdr = cmd_Exeits.ExecuteReader();
        while (rdr.Read())
        {
            Response.Write("<script language='JavaScript'>");
            Response.Write("alert('對不起,該產(chǎn)品編號已經(jīng)存在!')");
            Response.Write("</script>");
            this.txtCategoryId.Text = "";
            this.txtDescription.Text = "";
            this.txtName.Text = "";
            this.txtPrice.Text = "";
            this.txtProductId.Text = "";
            return;
        }
        rdr.Close();

        string sql_add = "insert into Product(ProductId,CategoryId,Name,Description,Price)values('" + ProductId + "','" + CategoryId + "','" + Name + "','" + Description + "','" + Price + "')";
        SqlCommand cmd_add = new SqlCommand(sql_add, myconn);//SqlCommand:表示要對SQL Server數(shù)據(jù)庫執(zhí)行的一個Transact-SQL語句或存儲過程
        cmd_add.ExecuteNonQuery();//對連接執(zhí)行Transact-SQL語句并返回受影響的行數(shù)。對于 UPDATE、INSERT 和 DELETE 語句,返回值為該命令所影響的行數(shù)。對于所有其他類型的語句,返回值為 -1。如果發(fā)生回滾,返回值也為 -1。
        myconn.Dispose();
        myconn.Close();
    }
[/CODE

[COLOR=Red]數(shù)據(jù)顯示篇[/COLOR]
[CODE]
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string id = Request.Params["id"];
            if (id == null || id.Trim() == "")
            {
                Response.Redirect("default.aspx");
                Response.End();
            }
            else
            {
                string sql_show = "select * from Product Where ProductId=" + id;
                SqlCommand cmd_show = new SqlCommand(sql_show, conn);
                conn.Open();
                SqlDataReader rd_show = cmd_show.ExecuteReader();//使用SqlDataReader對象讀取并返回一個記錄集
                shows.DataSource = rd_show;//指向數(shù)據(jù)源
                shows.DataBind();//綁定數(shù)據(jù)
                rd_show.Close();//關(guān)閉SqlDataReader
             }
         }
    }

數(shù)據(jù)修改篇

  protected void btnAdd_Click(object sender, EventArgs e)
    {
        string ProductId = this.lblProductId.Text;
        string CategoryId = this.txtCategoryId.Text;
        string Name = this.txtName.Text;
        string Description = this.txtDescription.Text;
        decimal Price = decimal.Parse(this.txtPrice.Text);
        string sql_edit = "update Product set CategoryId='" + CategoryId + "',Name='" + Name + "',Description='" + Description + "',Price='" + Price + "' where ProductId =" + ProductId;
        SqlCommand cmd_edit = new SqlCommand(sql_edit, conn);
        conn.Open();
        cmd_edit.ExecuteNonQuery();
        conn.Close();
        Response.Write("<script language=javascript>window.alert('保存成功!')</script>");
        Response.Redirect("show.aspx?id=" + ProductId);
    }

數(shù)據(jù)刪除篇

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string ProductId = Request.Params["id"];
            string sql_del = "delete from Product where ProductId=" + ProductId;
            SqlCommand cmd_del = new SqlCommand(sql_del, conn);
            conn.Open();
            cmd_del.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("default.aspx");
        }
    }

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“ASP.NET如何連接數(shù)據(jù)庫”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI