【C#/ASP.NET】数据库接口总结

操作系统:Windows10
IDE:Visual Studio + SQL Server

1. 数据库连接

1) 先在web.config文件中设置连接属性:

 <connectionStrings>  

 <add name="PhotoStudioConnectionString" connectionString="Data Source=DESKTOP4RPK98H; Initial Catalog=PhotoStudio; User ID=sa; Password=sql123" providerName="System.Data.SqlClient"**/>**  

 </connectionStrings>  

2) 变量描述

SqlConnection cn; //数据库连接  
string strCon =        ConfigurationManager.ConnectionStrings["PhotoStudioConnectionString"].ConnectionString;  //连接配置 

2. 为控件绑定数据

方法一:直接为控件添加数据源

添加工具中的SqlDataSource,选择所需表、列,即可简单绑定,该方法操作简单,适合静态数据的展示,用于多种控件,如GridView, DataList。但该方法不适合动态绑定的控件数据。例如Datalist数据绑定:

控件声明:

<asp:DataList ID="DataList_pkgIntro" runat="server" DataSourceID="SqlDataSource_pkgIntro" DataKeyField="packageID" >  
<ItemTemplate>  
    <table width="100%" align="center">  
      <tr>  
        <td align ="center" height:"auto" valign="top">   
          <asp:Image ID="Image2" runat="server"   
                   ImageUrl='<%# Eval("pkgImage") %>' />  
        </td>  

     </tr>**  
    </table>  

</ItemTemplate>  
 <!--其他代码-->   
</asp:DataList> 

数据源定义:

<asp:SqlDataSource ID="SqlDataSource_pkgIntro" runat="server"   
 ConnectionString="<%$ ConnectionStrings:PhotoStudioConnectionString %>"     
SelectCommand="SELECT [packageID], [pkgImage], [overview], [name] FROM [Package]">  
</asp:SqlDataSource>  

方法二:在.cs后端代码中动态绑定数据源

​ aspx.cs文件中:

public void bindAllorder()  
{  
     string cmdStr = 
     "EXEC pr_用户订单 @userID=1,@role='管理员',@status=null";  
     cn = new SqlConnection(strCon); //建立数据库连接  
     //创建DataAdapter数据适配器实例,以自定义SQL语句和数据库连接cn为参数  
     SqlDataAdapter da = new SqlDataAdapter(cmdStr, cn);
     DataSet ds = new DataSet(); //创建DataSet实例  
     cn.Open(); //打开数据库连接  
     da.Fill(ds); //填充数据集  
     if (ds.Tables[0].Rows.Count <= 0)//查询结果中的列数小于等于0,结果集为空  
        label_page.Text = "当前没有预约记录";  
     allorderGV.DataSource = ds; //allorderGV为gridview控件,数据源为ds  
    allorderGV.DataKeyNames = new string[] { "订单号" };//设置主键  
    allorderGV.DataBind();//数据绑定 
    cn.Close();//关闭连接  
 }  

定义函数后,在前端对gridview中某一行数据修改时,对数据库进行相应增删、改、改操作,然后调用bindAllorder(),即可重新绑定控件数据源。

3. 数据库增加记录

以用户注册为例:前端用户填写表格,填充各项相关信息,点击确认,触发bn_addUser_Click()函数,读取表格内各项信息,插入用户表。

提交button的响应函数:bn_addUser_Click()

protected void bn_addPhotographer_Click(object sender, EventArgs e)  
{  
  if (this.IsValid)  
  {  
    SqlConnection cn = new SqlConnection(strCon);  
    SqlCommand cmd_Tuser = 
      new SqlCommand("SET IDENTITY_INSERT Tuser OFF INSERT INTO Tuser(username,userpwd,gender,phonenumber,mail,role) VALUES (@username, @userpwd, @gender, @phonenumber, @mail,@role)", cn);  
      //不插入ID,自增  
      cmd_Tuser.Parameters.Add("@username", SqlDbType.VarChar).Value = txtUsername.Text;  
      cmd_Tuser.Parameters.Add("@userpwd", SqlDbType.VarChar).Value = txtPwd.Text;  
      cmd_Tuser.Parameters.Add("@gender", SqlDbType.VarChar).Value = bnGender.SelectedValue;  
      cmd_Tuser.Parameters.Add("@phonenumber", SqlDbType.Char).Value = txtPhone.Text;  
      cmd_Tuser.Parameters.Add("@mail", SqlDbType.VarChar).Value = txtMail.Text;  
       cmd_Tuser.Parameters.Add("@role", SqlDbType.VarChar).Value = "用户";  
    try  
     {  
        cn.Open();//打开数据库连接  
        cmd_Tuser.ExecuteNonQuery();//先向user表插入  
        Response.Write("<script>window.alert('新增成功!');window.location='myCenter_admin.aspx?page=allPhotographer'</script>");  
     }  
    catch  
    {  
     ClientScript.RegisterStartupScript(this.GetType(), "Key", "<script>alert('插入失败!');</script>");  
    }  
    finally  
    {  
        cn.Close();  
    }
  }
}  

4. 数据库删除记录

在gridview每一行记录的末端加入一个“删除”按钮,后台获取该行的主码值,触发删除操作,对应的事件为OnRowDeleting,触发函数:

protected void allorderGV_RowDeleting(object sender,GridViewDeleteEventArgs e)  
{  
      string cmdStr = "delete from TOrder where orderID='" 
       + allorderGV.DataKeys[e.RowIndex].Value.ToString() + "'";  
      cn = new SqlConnection(strCon);  
      cmd = new SqlCommand(cmdStr, cn);  
      cn.Open();  
      cmd.ExecuteNonQuery();  
      cn.Close();  
      allorderGV.DataBind();  
      bindAllorder();  
}  

5. 数据库更新记录

与删除操作原理相同,对应的事件为OnRowUpdating。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值