C#DataSet/DataAdapter
2024-09-21 11:42:57
DataReader必须持续连接,所以在调用方法SqlDataReader作为返回类型时候,必须在方法外关闭流,很不方便。
DataAdapter用于对数据源检索数据并填充到DataSet中的表。DataAdapter还可以将DataSet所做的更改进行解析回数据源。
(通俗点,DataSet就是一个缓冲区,可以修改好数据,让DataAdapter返回回数据源)
DataAdapter使用例程
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; namespace DataAdapter
{
public partial class Form1 : Form
{
string constr = "server=QT-201303030913;database=ThreeDb;uid=sa;pwd=daxiang";
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//Bind();
} private void Bind()
{ string sql = "select * from product";
SqlDataAdapter sda = new SqlDataAdapter(sql, constr);
DataSet ds = new DataSet();
sda.Fill(ds); dataGridView1.DataSource = ds.Tables[];
} private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("select * from product", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds,"product"); dataGridView1.DataSource = ds.Tables["product"];
}
} private void button2_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("select * from product", constr);
DataSet ds = new DataSet();
sda.Fill(ds,"p"); dataGridView1.DataSource = ds.Tables["p"];
} private void button3_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("select * from product", constr);
DataSet ds = new DataSet();
sda.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"]; sda.SelectCommand.CommandText = "select * from classify";
sda.Fill(ds,"c");
dataGridView2.DataSource = ds.Tables["c"];
} private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
string concell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
string msg = string.Format("您单击的是第{0}行的第{1}列\n当前单元格的内容为\"{2}\"",e.RowIndex.ToString(),e.ColumnIndex.ToString(),concell);
MessageBox.Show(msg);
} }
}
form1设计
在一个DataSet中多张表名存在大小写,则搜索表名倍认为存在大小写,否则补区分大小写。
最新文章
- UCOSII内核代码分析
- resize
- HTML5(常用的表单控件)
- 通过dblink的方式查看表的结构
- 读书笔记2014第3本:Visual Studio程序员箴言
- 怎样下载完整的Spring包
- world符号大全
- 从一个脚本谈loadrunner的脚本初始化
- 【转】Mac QQ截图保存在哪里?
- [转]SharePoint 2010/2013 使用Javascript来判断权限的三种方法
- linux 文件查找和压缩工具
- MFC内部结构剖析
- xpath, urllib
- Win10 x64 + CUDA 10.0 + cuDNN v7.5 + TensorFlow GPU 1.13 安装指南
- D - 文理分科 (网络流->;最小割)
- 编程:在屏幕中间分别显示绿色、绿底红色、白底蓝色的字符串'welcome to masm!'
- English trip -- Review Unit7 Shopping 购物
- 【Maven学习】Maven打包生成普通jar包、可运行jar包、包含所有依赖的jar包
- SPOJ4717——Grid Points in a Triangle
- 通过logstash收集mysql慢查询日志转换为json