星尘小组第七周学习笔记——ADO.Net中DataTable的应用

第七周学习笔记

ADO.Net中DataTable的应用

知识点描述、思维导图、示例代码、效果截图

(一) 知识点描述

DataTable介绍: 表示一个内存内关系数据的表,可以独立创建和使用,也可以由其他 .NET Framework对象使用,最常见的情况是作为 DataSet 的成员使用。

  1. 1.       创建DataTable对象:声明并实例化数据表,用于保存数据库中调出的数据,以用作为数据源

DataTable Table1 = new DataTable();

【补充】

还有另一种通过调用DataSet的Tables对象,用Add方法创建DataTable对象的方法:

DataSet dataset = new dataSet( );

DataTable table = dataset.Tables.Add(“Table1”);

  1. 2.       填充DataTable对象(以连接SQL Sever类型数据库为例):

1)       声明并实例化SQL命令(SqlCommand)、SQL数据适配器(SqlDataAdapter);

2)       将SQL命令的连接属性指向SQL连接;

3)       将SQL数据适配器的查询命令属性指向SQL命令;

4)       打开SQL连接,SQL数据适配器读取数据,并填充数据表;

SqlCommand sqlCommand = new SqlCommand();

sqlCommand.Connection = sqlConnection;

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

sqlCommand.CommandText ="SELECT * FROM tb_list ;";

sqlDataAdapter.SelectCommand = sqlCommand;

sqlConnection.Open();  

sqlDataAdapter.Fill(this.Table1);

sqlConnection.Close();        

填充好的数据表,可以作为数据网格视图对象(DataGridView)的数据源,在网格视图中显示数据表内容

this.dataGridView1.DataSource = Table1;  

  1. 3.       在DataTable中创建行

1)      为原数据表创建新的行

给原数据表新建一个数据行(使用方法NewRow),该行的状态为【附加】

DataRow  Row2 = this.Table1.NewRow();                               

2)      为新创建的行赋值

  1. 可以直接为新建数据行赋值

Row2["Name"] = “张三”;

Row2["No"] = 20;

  1. 可以绑定已有数据网格视图中的数据行,转换其类型为数据行视图类型(DataRowView),并获取数据行

DataRowRow1=((DataRowView)this.dataGridView1.CurrentRow.DataBoundItem).Row使用这种方法新创建的数据行,需要逐一将从原数据网格视图获取的数据行的各列值,赋予已新创建数据行的相应列;

Row2["No"] = Row1["No"];

Row2["Name"] = Row1["Name"];

Row2["Credit"] = Row1["Credit"];

3)      将添加行至原数据表

利用Add方法将新创建的DataRow对象加入原数据表;随后该行的状态为【添加】this.Table1.Rows.Add(Row2);

  1. 4.       在DataTable中删除行

1)      删除行

当前数据行删除;随后该行的状态为删除

Row1.Delete(); 

2)      撤销“行的删除”

  1. 声明已删课程数据行(即先前从原数据表中删除的数据行);

已删课程数据行可通过课程数据表的方法Select查得,该方法接受查询条件、排序条件、行状态条件等参数,并返回数据行数组;

  1. 已删课程数据行拒绝更改,即回滚先前对其执行的删除;随后该行的状态为【未更改】;

DataRow Row3 =  this.Table1.Select("No='123'", "",DataViewRowState.Deleted)[0];

Row3.RejectChanges();

  1. 行的移除

从数据表的行集合中移除当前数据行,随后该行的状态为【附加】;

this.Table1.Rows.Remove(Row2);

  1. 5.       DataTable更新数据库

1)      更新DataTable:声明数据表,并指向更改后的数据网格视图的数据源

【注意】数据源默认类型为object,还需强制转换类型

DataTable Table2 = (DataTable)this.dataGridView1.DataSource;

2)      绑定DataTable中的列名

向SQL命令的参数集合添加参数的名称、SQL Server数据类型、长度(仅用于定长类型)、所绑定的DataTable的列名;

sqlCommand.Parameters.Add("@Name",SqlDbType.VarChar,0,"Name");                                 

sqlCommand.Parameters.Add("@Gender", SqlDbType.Bit, 0, "Gender");

3)      更新数据库

  1. 声明并实例化SQL数据适配器,同时借助构造函数,将其SelectCommand属性设为先前创建的SQL命令

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

sqlDataAdapter.UpdateCommand = sqlCommand;

  1. 打开SQL连接;SQL数据适配器根据学生数据表提交更新,并返回受影响行数

sqlConnection.Open();

int rowAffected = sqlDataAdapter.Update(Table2);

sqlConnection.Close();     

  1. 6.       DataTable的查询

1)      Select查询

声明并实例化查询返回的行数据(DataRow)集合

利用数据表的自有方法Select进行查询

  • 该方法的效率最低。

DataRow[] Rows1 =this.Table1.Select("Pinyin LIKE '%" + this.textBox0.Text.Trim() + "%'");

2)      Find查询

Find:数据表的【行集合】的方法Find,根据主键值快速查找,并返回其所在的数据行;

DataRow Row5 = this.Table1.Rows.Find(this.textBox0.Text.Trim());

3)      FindRows查询

FindRows: 数据视图的方法FindRows,根据排序列快速查找,并返回数据行视图数组

DataRowView[] DataRowViews1 = this.Table1.FindRows(this.textBox1.Text.Trim());

4)      将查询结果写入数据表

  1. 将查询所得数据行导入(ImportRow方法)至指定数据表中

可将数据网格视图的数据源设为搜索结果数据表,用以显示结果

Table1.ImportRow(Row5);

this.dataGridView1.DataSource = Table1;

  1. 对于查询结果为多条数据,即数据行视图数组、行数据(DataRow)集合等

foreach:遍历搜索结果所在数据行视图数组

foreach (DataRowView dataRowView1 in DataRowViews1)

{

Table1.ImportRow(dataRowView1.Row);

}

若存储结果的为行数据(DataRow)集合,同理:

 foreach (DataRow row in Rows1)

{

searchResultTable.ImportRow(row);

}

  1. 7.       DataTable的克隆与复制

1)      Clone 方法:克隆 DataTable 的结构,包括所有 DataTable 架构和约束

DataTable Table1 = this.Table2.Clone();

2)      Copy 方法:复制该 DataTable 的结构和数据

DataTable Table1 = this.Table2.Copy();

(二) 思维导图

 

 

(三) 代码示例

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WindowsFormsApplication1

{

    public partial class Form_datatable : Form

    {

            public Form_datatable()

        {

            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterScreen;       

        }

        private void btn_load_Click_1(object sender, EventArgs e)

        {

           SqlConnection sqlConnection = new SqlConnection();

            sqlConnection.ConnectionString =

                ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;

            SqlCommand sqlCommand = new SqlCommand();                                                   

            sqlCommand.Connection = sqlConnection;                                                     

            sqlCommand.CommandText = "SELECT * FROM tb_prengant ;";                                         

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                       

            sqlDataAdapter.SelectCommand = sqlCommand;                                                

            DataTable prengant = new DataTable();                                                

            sqlConnection.Open();                                                                   

            sqlDataAdapter.Fill(prengant);                                                          

            sqlConnection.Close();                                                                  

            this.dGV_prengant.DataSource = prengant;                                                  

       

        }

        private void btn_update_Click_1(object sender, EventArgs e)

        {

            {

            SqlConnection sqlConnection = new SqlConnection();

            sqlConnection.ConnectionString =

                ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;

            SqlCommand insertCommand = new SqlCommand();                                                  

            insertCommand.Connection = sqlConnection;                                                 

            insertCommand.CommandText =                                                               

                 "INSERT tb_prengant (care_no,household,name,age,husband,birthdate,career,culture,telephone,ID,birth_certificate) VALUES(@care_no,@household,@name,@age,@husband,@birthdate,@career,@culture,@telephone,@ID,@birth_certificate);";

            insertCommand.Parameters.Add("@care_no", SqlDbType.VarChar, 10, "care_no");

            insertCommand.Parameters.Add("@household", SqlDbType.VarChar, 20, "household");

            insertCommand.Parameters.Add("@name", SqlDbType.VarChar, 20, "name");

            insertCommand.Parameters.Add("@age",SqlDbType.VarChar,20,"age");

            insertCommand.Parameters.Add("@husband",SqlDbType.VarChar,20, "husband");

            insertCommand.Parameters.Add("@birthdate",SqlDbType.VarChar,20, "birthdate");

            insertCommand.Parameters.Add("@career", SqlDbType.VarChar,20, "career");

            insertCommand.Parameters.Add("@culture", SqlDbType.VarChar,20, "culture");

            insertCommand.Parameters.Add("@telephone",SqlDbType.VarChar,20, "telephone");

            insertCommand.Parameters.Add("@ID", SqlDbType.VarChar,20, "D");

            insertCommand.Parameters.Add("@birth_certificate", SqlDbType.VarChar,20, "birth_certificate");

            SqlCommand updateCommand = new SqlCommand();                                                 

            updateCommand.Connection = sqlConnection;                                                    

            updateCommand.CommandText =                                                                   

                 "UPDATE tb_prengant"

                + " SET  care_no=@care_no, household=@household,name=@name,age=@age,husband=@husband,birthdate=@birthdate,career=@career,culture=@culture,telephone=@telephone,ID=@ID,birth_certificate=@birth_certificate;"

                + " WHERE care_no=@care_no;";

            updateCommand.Parameters.Add("@care_no", SqlDbType.VarChar, 10, "care_no");

            updateCommand.Parameters.Add("@household", SqlDbType.VarChar, 20, "household");

            updateCommand.Parameters.Add("@name", SqlDbType.VarChar, 20, "name");

            updateCommand.Parameters.Add("@age",SqlDbType.VarChar,20,"age");

            updateCommand.Parameters.Add("@husband",SqlDbType.VarChar,20, "husband");

            updateCommand.Parameters.Add("@birthdate",SqlDbType.VarChar,20, "birthdate");

            updateCommand.Parameters.Add("@career", SqlDbType.VarChar,20, "career");

            updateCommand.Parameters.Add("@culture", SqlDbType.VarChar,20, "culture");

            updateCommand.Parameters.Add("@telephone",SqlDbType.VarChar,20, "telephone");

            updateCommand.Parameters.Add("@ID", SqlDbType.VarChar,20, "D");

            updateCommand.Parameters.Add("@birth_certificate", SqlDbType.VarChar,20, "birth_certificate");

            SqlCommand deleteCommand = new SqlCommand();                                                 

            deleteCommand.Connection = sqlConnection;                                                    

            deleteCommand.CommandText =                                                              

                "DELETE tb_prengant"

                + " WHERE care_no=@care_no;";

            deleteCommand.Parameters.Add("@care_no", SqlDbType.VarChar, 10, "care_no");

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                      

            sqlDataAdapter.InsertCommand = insertCommand;                                              

            sqlDataAdapter.UpdateCommand = updateCommand;                                                 

            sqlDataAdapter.DeleteCommand = deleteCommand;                                               

            DataTable prengant = (DataTable)this.dGV_prengant.DataSource;                              

            sqlConnection.Open();

            int rowAffected = sqlDataAdapter.Update(prengant);                                 

            sqlConnection.Close();                                                                   

            MessageBox.Show("更新" + rowAffected.ToString() + "行。");

        }

        }

        }                                        

    }

 

(四) 效果截图

 

 

转载于:https://www.cnblogs.com/hawking-520/p/10714727.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值