ASP.NET连接SQL数据库(二)

//DataAdapter对象的两个主要方法
//fill方法,填充数据集
//update方法:向数据库提交存储在数据集中的更改
//    原理:使用Update方法自动遍历DataTable中的所有行,以检查需要对数据库作出的变动,它为每一发生更改的行调用insert update delete命令

//DataTable的Rows集合的三个常用方法
//find方法:检索行
//add方法:创建行
//delete方法:删除行
using System;
using System.Data;
using System.Configuration;
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;

using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connStr = "server=localhost;database=pubs;uid=sa;pwd=123456";
        //string str = System.Configuration.ConfigurationManager.ConnectionStrings[connStr].ToString();
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        SqlDataAdapter sda = new SqlDataAdapter("select * from authors", conn); 
        //SqlCommandBuilder类,自动生成单表命令,在更新单一表的简单情况下,我们不需要知道如何编写SQL语句以完成更新
        SqlCommandBuilder scb = new SqlCommandBuilder(sda);//生成SQL命令并与DataAdapter连接
        DataSet ds = new DataSet();
        sda.Fill(ds, "authors");//在使用DataSet前,我们必须将来自数据库的数据填充它
      
        //添加数据
        DataRow dr=ds.Tables["authors"].NewRow();//新建一行空的
        dr["au_id"] = "999-99-9999";
        dr["au_fname"] = "wang";
        dr["au_lname"] = "jun";
        dr["phone"] = "999 999-0752";
        dr["address"] = "aaaaaaa";
        dr["city"] = "BJ";
        dr["state"] = "ZG";
        dr["zip"] = "100101";
        dr["contract"] = 1;
        ds.Tables["authors"].Rows.Add(dr);//向行中添加数据

        //修改数据
        Response.Write("修改之前的数据为:");
        Response.Write("au_id:" + ds.Tables["authors"].Rows[0][0]);
        Response.Write("au_fname:" + ds.Tables["authors"].Rows[0][1]);
        Response.Write("au_lname:" + ds.Tables["authors"].Rows[0][2]);

        Response.Write("<br>");
        ds.Tables["authors"].Rows[0][1] = "jun";
        ds.Tables["authors"].Rows[0][2] = "wang";

        Response.Write("修改之前的数据为:");
        Response.Write("au_id:" + ds.Tables["authors"].Rows[0][0]);
        Response.Write("au_fname:" + ds.Tables["authors"].Rows[0][1]);
        Response.Write("au_lname:" + ds.Tables["authors"].Rows[0][2]);

        //删除数据
        ds.Tables["authors"].Rows[0].Delete();
        sda.Update(ds, "authors");
        Response.Write("数据已删除!");

        conn.Close();

    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值