第七周学习笔记
ADO.Net中DataTable的应用
- 知识点描述
ADO.NET可以在与数据库断开连接的方式下通过DataTable对象进行数据处理,当需要更新数据时才重新与数据源进行连接,并更新数据源。DataTable对象表示保存在本机内存中的表,它提供了对表中行列数据对象的各种操作。同时还可以进行相对应的增删改查的相对应的操作
基本属性有五种:
- Columns 表示列的集合
- Constraints 特定DataTable的约束集合
- DataSet 所属的数据集
- PrimaryKey 主键
- Rows 表示行的集合
- TableName
接下来是常用的构造函数方法
一种是ADO.NET DataTable构造函数方法,创建DataTable对象的实例,以表名字符串作为参数;
另外一种为创建DataTable对象的实例,无参数。创建后,再修改TableName属性,给表设定表名。
基本方法在思维导图中都有呈现出来。
- 代码和示例
运行结果:
代码:
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=YiMiao;Integrated Security=sspi";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_YiMiao;";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
this.YiMiaoTable = new DataTable();
sqlConnection.Open();
sqlDataAdapter.Fill(this.YiMiaoTable);
sqlConnection.Close();
this.YiMiaoByName = new DataView();
this.YiMiaoByName.Table = this.YiMiaoTable;
this.YiMiaoByName.Sort = "YMName ASC";
this.dgv_YiMiao.Columns.Clear();
this.dgv_YiMiao.DataSource = this.YiMiaoTable;
this.dgv_YiMiao.Columns["ID"].HeaderText = "编号";
this.dgv_YiMiao.Columns["YMName"].HeaderText = "疫苗名称";
this.dgv_YiMiao.Columns["producecom"].HeaderText = "生产公司";
this.dgv_YiMiao.Columns["category"].HeaderText = "类型";
this.dgv_YiMiao.Columns["Money"].HeaderText = "价格";
this.dgv_YiMiao.Columns["Beizhu"].Visible = false;
- 思维导图