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[0]; } 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}列 当前单元格的内容为"{2}"",e.RowIndex.ToString(),e.ColumnIndex.ToString(),concell); MessageBox.Show(msg); } } }
form1设计
在一个DataSet中多张表名存在大小写,则搜索表名倍认为存在大小写,否则补区分大小写。