数据适配器对象(DataAdapter)

一、DataAdapter对象概述

1、 DataAdapter是一个特殊的类,其作用是数据源与DataSet对象之间沟通的桥梁。 2、 DataAdapter提供了双向的数据传输机制

(1) 在数据源上执行Select语句,把查询结果集传送到DataSet对象的数据表(DataTable)中。 (2)执行Insert、Update和Delete语句,将更改过的数据提取并更新回数据源。

二、DataAdapter对象的常用属性和常用方法

1、 常用的创建SqlDataAdapter对象的语法格式

SqlDataAdapter 对象名=new SqlDataAdapter(SqlStr,conn);

其中: SqlStr为Select查询语句或SqlCommand对象 , conn为SqlConnection对象。

2、常用的属性

3、常用的方法

(1)Fill方法:调用Fill方法会自动执行SelectCommand属性中提供的命令,获取结果集并填充数据集的DataTable对象。

其本质是通过执行SelectCommand的Select语句查询数据库,返回DataReader对象,通过DataReader对象隐式地创建DataSet中的表,并填充DataSet中表行的数据。

(2)Update方法调用InsertCommand、UpdateCommand和DeleteCommand属性指定的SQL命令,将DataSet对象更新到相应的数据源。

在Update方法中,逐行检查数据表每行的RowState属性值,根据不同的RowState属性,调用不同的Command命令更新数据库。DataAdapter对象更新数据库示例图如图所示。

(3) DataTable对象

DataTable对象是内存中一个关系数据库表,可以独立创建也可以由DataAdapter来填充。

声明一个DataTable对象的语法格式如下所示:

使用两条语句:

DataTable 对象名 = new DataTable();

对象名.TableName="数据表名";

或 使用一条语句:

DataTable 对象名 = new DataTable("数据表名");

例如:创建数据表对象dtStu,代码如下:

// 创建一个新的 DataTable 对象用于存储学生信息数据

DataTable dtStu = new DataTable();

// 设置 DataTable 的 TableName 属性为 "StuInfo",标识该 DataTable 中存储的是学生信息数据

dtStu.TableName = "StuInfo";

或者:

// 使用构造函数创建一个新的 DataTable 对象,并设置其 TableName 属性为 "StuInfo",用于存储学生信息数据

DataTable dtStu = new DataTable("StuInfo");

一个DataTable对象创建后,通常需要调用DataAdapter的Fill()对其进行填充,使DataTable对象获得具体的数据集,而不再是一个空表对象。

调用DataAdapter的Fill()对datatable进行填充: SqlDataAdapter.Fill(DataTable对象);

DataTable对象的常用属性

DataTable对象的常用属性主要有Columns属性、Rows属性和DefaultVIew属性。

Columns属性:获取DataTable对象中表的列集合。Rows属性:获取DataTable对象中表的行集合。NewRow()方法:创建一个与当前数据表有相同字段结构的数据行。Clear()方法:清除表中所有的数据。DefaultView属性:获取可能包括筛选视图或游标位置的表的自定义视图。DataSet属性:获取DataTable对象所属的DataSet对象。PrimaryKey属性:获取或设置数据表的主键。TableName属性:获取或设置数据表名。

4、SqlCommandBuilder 对象

利用 SqlCommandBuilder 对象能够自动生成: InsertCommand 、UpdateCommand、 DeleteCommand。

定义语句:

SqlCommandBuilder builder = new SqlCommandBuilder(DataAdapter对象);

三、使用步骤

1、创建数据库连接对象。

2、利用数据库连接对象和Select语句创建SqlDataAdapter对象。

3、利用SqlCommandBuilder对象能够自动生成SqlDataAdapter对象的InsertCommand、UpdateCommand、DeleteCommand属性。

SqlCommandBuilder builder =new SqlCommandBuilder(DataAdapter对象);

4、使用SqlDataAdapter对象的Fill方法把Select语句的查询结果放在DataSet对象的一个数据表中或直接放在一个DataTable对象中。

SqlDataAdapter.Fill(DataTable对象);

5、对DataTable对象中的数据进行增、删、改操作。

6、修改完成后,通过SqlDataAdapter对象的Update方法将DataTable对象中的修改更新到数据库。

SqlDataAdapter.Update();

四、使用实例

在前面的文章中,我们学习了使用记录表和datareader对象来实现数据库的显示,但是我们可以看到使用前两种方法之前都需要和数据库连接,但是如果我们想要实现离线连接数据库(即不使用myconnection.Open();),那么我们就需要使用DataAdapter对象。

使用DataAdapter对象的时候,也需要Gridview控件的参与:

结果:

实现代码:

protected void Button11_Click(object sender, EventArgs e)

{

// 设置数据库连接字符串

myconnection.ConnectionString = sqlcon;

// 定义 SQL 查询语句

string sqlcmd = "select * from studentscore";

// 创建 SqlDataAdapter 对象,并传入 SQL 查询语句和数据库连接对象

SqlDataAdapter da = new SqlDataAdapter(sqlcmd, myconnection);

// 创建 DataTable 对象

DataTable dt = new DataTable();

// 使用 SqlDataAdapter 填充 DataTable

da.Fill(dt);

// 将 DataTable 设置为 GridView 的数据源

GridView2.DataSource = dt;

// 绑定数据到 GridView

GridView2.DataBind();

}

如果想要实现,使用DataAdapter对象进行更新数据库,那么应该怎么做呢?

实现结果:

实现代码:

protected void Button12_Click(object sender, EventArgs e)

{

// 设置数据库连接字符串

myconnection.ConnectionString = sqlcon;

// 定义 SQL 查询语句

string sqlcmd = "select * from studentscore";

// 创建一个 SqlDataAdapter 对象,用于执行 SQL 查询并将结果填充到 DataTable 中

SqlDataAdapter da = new SqlDataAdapter(sqlcmd, myconnection);

// 创建一个 DataTable 对象,用于存储查询结果

DataTable dt = new DataTable();

// 使用 SqlDataAdapter 填充 DataTable,从数据库中检索数据

da.Fill(dt);

// 使用 SqlCommandBuilder 自动为 SqlDataAdapter 生成 SQL 命令,用于更新数据库

SqlCommandBuilder builder = new SqlCommandBuilder(da);

// 创建一个新的 DataRow 对象用于存储新数据

DataRow myrow = dt.NewRow();

// 为新 DataRow 对象的每个列赋值

myrow[0] = "4"; // 列索引为 0

myrow[1] = TextBox3.Text; // 列索引为 1,从 TextBox3 中获取值

myrow[2] = TextBox4.Text; // 列索引为 2,从 TextBox4 中获取值

myrow[3] = TextBox5.Text; // 列索引为 3,从 TextBox5 中获取值

// 将新行添加到 DataTable 中

dt.Rows.Add(myrow);

// 使用 SqlDataAdapter 更新数据库中的数据

da.Update(dt);

// 重定向到 webform1.aspx 页面

Response.Redirect("webform1.aspx");

}

五、补充(表格输出方式显示详细信息或者删除某条语句)

前面我们使用select方式删除过某条语句,但是如果我们在运行的时候看到某条语句的时候,我们想要删除或者查看它的详细信息,我们应该如何实现呢?依旧使用上面的数据库。

在前面的显示中我们可以看到,只有显示数据库里的内容,而没有对他的操作,所以,我们想要实现对数据库的操作,我们首先需要多加名为操作的一列。直接在前一篇

数据读取对象(DataReader)-CSDN博客的二、DataReader的使用示例的基础上添加:

查看详细信息或者删除的话,就可以直接跳转到另一个界面,这个界面也需要访问数据库,所以也需要配置参数。

添加之后的结果(这里删除了一个,忘记截图了)

然后点击第一条的查看详细信息:

删除的话,就直接就删除了,就在不删了。

webform1.aspx文件代码:

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


webform1.aspx.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;

using System.Configuration;

namespace WebApplication9

{

public partial class deleteTable : System.Web.UI.Page

{

string sqlcon = ConfigurationManager.ConnectionStrings["studentcnnstring"].ToString();

//然后建立链接对象

SqlConnection myconnection = new SqlConnection();

protected void Page_Load(object sender, EventArgs e)

{

myconnection.ConnectionString = sqlcon;

}

protected void Button1_Click(object sender, EventArgs e)

{

myconnection.Open();

string sqlcmd = "select * from studentscore";

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

SqlDataReader myreader = mycommand.ExecuteReader();

Response.Write("遍历数据:
");

Response.Write("

");

Response.Write("

");//表示行

for (int i = 0; i < myreader.FieldCount; i++)//使用FieldCount获取当前行中的列数

{

Response.Write("

");//td表示列,使用GetName获取每一列的名称

}

Response.Write("

");//读完数据库中的数据名称之后,在表格中添加表头为操作的一列

Response.Write("

");

Response.Write("

");

//下面就是读数据库中的每一行内容,然后输出,按行读即read方法,然后使用FieldCount获取当前行中的列数,然后依次输出

while (myreader.Read())

{

Response.Write("

");

for (int i = 0; i < myreader.FieldCount; i++)

{

Response.Write("

");

}

Response.Write("

");

Response.Write("

");

Response.Write("

");

}

Response.Write("

" + myreader.GetName(i) + " 操作1 操作2
" + myreader[i].ToString() + " 查看详细信息 删除
");

myconnection.Close();

}

}

}

查看详细信息和删除之后的文件:

webform2.aspx文件代码:

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


id

name

sex

score

webform2.aspx.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;

using System.Configuration;

namespace WebApplication9

{

public partial class WebForm2 : System.Web.UI.Page

{

string sqlcon = ConfigurationManager.ConnectionStrings["studentcnnstring"].ToString();

SqlConnection myconnection = new SqlConnection();

protected void Page_Load(object sender, EventArgs e)

{

myconnection.ConnectionString = sqlcon;

myconnection.Open();

string id = Request.QueryString["id"];

string Delid = Request.QueryString["delid"];

//Response.Write("接收id为" + id);

if (id != null)

{

string sqlcmd = "select * from studentscore where id=" + id;

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

SqlDataReader myreader = mycommand.ExecuteReader();

while (myreader.Read())

{

Label1.Text = myreader.GetValue(0).ToString();

Label2.Text = myreader.GetValue(1).ToString();

Label3.Text = myreader.GetValue(2).ToString();

Label4.Text = myreader.GetValue(3).ToString();

TextBox1.Text = myreader.GetValue(0).ToString();

TextBox2.Text = myreader.GetValue(1).ToString();

TextBox3.Text = myreader.GetValue(2).ToString();

TextBox4.Text = myreader.GetValue(3).ToString();

}

//下面注释掉的这是按照前面的表格方法显示的,但是往往不使用这种方法

//Response.Write("

");

//Response.Write("

");

//for (int i = 0; i < myreader.FieldCount; i++)

//{

// Response.Write("

");

//}

//Response.Write("

");

//while (myreader.Read())

//{

// Response.Write("

");

// for (int i = 0; i < myreader.FieldCount; i++)

// {

// Response.Write("

");

// }

// Response.Write("

");

//}

//Response.Write("

" + myreader.GetName(i) + "
" + myreader.GetValue(i) + "
");

}

if (Delid != null)

{

string sqlcmd = "delete from studentscore where id=" + Delid;

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

mycommand.ExecuteNonQuery();

Response.Redirect("webform1.aspx");

}

myconnection.Close();

}

}

}

在上面的查看详细信息中,发现,我使用了两种控件,label和textbox控件, 这是因为label只能显示,而textbox可以实现修改,如果我感觉这个信息不合适,就直接在textbox中修改,然后直接更新,要怎么实现呢?

我本来想的是下面语句,但是无法实现:

protected void Button1_Click(object sender, EventArgs e)

{

myconnection.Open();

string id = TextBox1.Text ;

string name = TextBox2.Text;

string sex = TextBox3.Text;

string score = TextBox4.Text;

string sqlcmd = "update studentscore set name='" + name + "', sex='" + sex + "', score='" + score + "' where id='" + id + "'";

//string sqlcmd = "insert into studentscore(name,sex,score,id) values('" + name + "', '" + sex + "', '" + score + "','" + id + "')";

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

//SqlDataReader myreader = mycommand.ExecuteReader();

mycommand.ExecuteNonQuery();

myconnection.Close();

}

然后,我就查看了一下整体的代码,发现,我在接受数据的时候,是在初始化状态下接受的,在这种情况下,显示的数据库永远是从上一个网站中传过来的,而不是更新后的,所以,我就在初始化状态下添加了一个判断语句,使用Ispostback方法,显示一次,后面显示的即为修改后的数据库。整体的代码如下:

webform1.aspx.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;

using System.Configuration;

namespace WebApplication9

{

public partial class WebForm2 : System.Web.UI.Page

{

string sqlcon = ConfigurationManager.ConnectionStrings["studentcnnstring"].ToString();

SqlConnection myconnection = new SqlConnection();

protected void Page_Load(object sender, EventArgs e)

{

myconnection.ConnectionString = sqlcon;

myconnection.Open();

string id = Request.QueryString["id"];

string Delid = Request.QueryString["delid"];

//Response.Write("接收id为" + id);

if (!IsPostBack)

{

if (id != null)

{

string sqlcmd = "select * from studentscore where id=" + id;

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

SqlDataReader myreader = mycommand.ExecuteReader();

while (myreader.Read())

{

Label1.Text = myreader.GetValue(0).ToString();

Label2.Text = myreader.GetValue(1).ToString();

Label3.Text = myreader.GetValue(2).ToString();

Label4.Text = myreader.GetValue(3).ToString();

TextBox1.Text = myreader.GetValue(0).ToString();

TextBox2.Text = myreader.GetValue(1).ToString();

TextBox3.Text = myreader.GetValue(2).ToString();

TextBox4.Text = myreader.GetValue(3).ToString();

}

//Response.Write("

");

//Response.Write("

");

//for (int i = 0; i < myreader.FieldCount; i++)

//{

// Response.Write("

");

//}

//Response.Write("

");

//while (myreader.Read())

//{

// Response.Write("

");

// for (int i = 0; i < myreader.FieldCount; i++)

// {

// Response.Write("

");

// }

// Response.Write("

");

//}

//Response.Write("

" + myreader.GetName(i) + "
" + myreader.GetValue(i) + "
");

}

if (Delid != null)

{

string sqlcmd = "delete from studentscore where id=" + Delid;

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

mycommand.ExecuteNonQuery();

Response.Redirect("webform1.aspx");

}

}

myconnection.Close();

}

protected void Button1_Click(object sender, EventArgs e)

{

myconnection.Open();

string id = TextBox1.Text ;

string name = TextBox2.Text;

string sex = TextBox3.Text;

string score = TextBox4.Text;

string sqlcmd = "update studentscore set name='" + name + "', sex='" + sex + "', score='" + score + "' where id='" + id + "'";

//string sqlcmd = "insert into studentscore(name,sex,score,id) values('" + name + "', '" + sex + "', '" + score + "','" + id + "')";

SqlCommand mycommand = new SqlCommand(sqlcmd, myconnection);

//SqlDataReader myreader = mycommand.ExecuteReader();

mycommand.ExecuteNonQuery();

myconnection.Close();

Response.Redirect("webform1.aspx");

//Response.Redirect("deleteTable.aspx");

}

}

}

成功实现修改。

好了,今天就先这样吧。。