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

来源:互联网 发布:傅园慧 知乎 编辑:程序博客网 时间:2024/05/16 18:56

//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();

    }
}