1.DataSet的显示
string connStr = "server=.;uid=sa;pwd=123;database=testDb"; using (SqlConnection conn = new SqlConnection(connStr)) { //实例化一个数据集 DataSet ds = new DataSet(); //数据适配器,用于DataSet和SQL数据库的连接 SqlDataAdapter sda = new SqlDataAdapter("select * from employee ", conn); //在DataSet中添加或刷新行 sda.Fill(ds); //将ds中的表显示到dataGridView1控件中 dataGridView1.DataSource = ds.Tables[0]; }
2.DataSet的合并
string connStr = "server=.;uid=sa;pwd=123,;database=testDb"; using (SqlConnection conn = new SqlConnection(connStr)) { //实例化数据集ds1 DataSet ds1 = new DataSet(); SqlDataAdapter sda1 = new SqlDataAdapter("select * from employee", conn); sda1.Fill(ds1); //实例化数据集ds2 DataSet ds2 = new DataSet(); SqlDataAdapter sda2 = new SqlDataAdapter("select * from testTable2", conn); //在DataSet中添加或刷新行 sda2.Fill(ds2); //将ds2与ds1合并,并处理不兼容的架构 ds1.Merge(ds2, true,MissingSchemaAction.AddWithKey); this.dataGridView1.DataSource = ds1.Tables[0]; }
3.DataSet的复制
//数据集ds1 DataSet ds1; private void Form1_Load(object sender, EventArgs e) { string connStr = "server=.;uid=sa;pwd=123;database=TestDb"; using (SqlConnection conn = new SqlConnection(connStr)) { //SqlDataAdapter 数据一次性加载完成,连接就关闭了(数据量大的时候) //SqlDataReader 数据一行一行读取,需要手动关闭连接(数据量小的时候) using (SqlDataAdapter sda = new SqlDataAdapter("select * from employee", conn)) { ds1 = new DataSet(); sda.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0]; } } }
private void button1_Click(object sender, EventArgs e) { //复制ds1的数据和结构到ds2 DataSet ds2 = ds1.Copy(); dataGridView2.DataSource = ds2.Tables[0]; }
4.DataSet的更新
DataSet ds1; SqlDataAdapter sda; private void button1_Click(object sender, EventArgs e) { string connStr = "server=.;uid=sa;pwd=123;database=TestDb"; //SqlConnection conn = new SqlConnection(connStr); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from employee"; sda = new SqlDataAdapter(); sda.SelectCommand = cmd; ds1 = new DataSet(); sda.Fill(ds1, "oldDs"); dataGridView1.DataSource = ds1.Tables[0]; } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox1.Text = dataGridView1.SelectedCells[0].Value.ToString(); textBox2.Text = dataGridView1.SelectedCells[1].Value.ToString(); textBox3.Text = dataGridView1.SelectedCells[2].Value.ToString(); textBox4.Text = dataGridView1.SelectedCells[3].Value.ToString(); textBox5.Text = dataGridView1.SelectedCells[4].Value.ToString(); } private void button2_Click(object sender, EventArgs e) { DataTable dt = ds1.Tables["oldDs"]; //将表结构加载到表中 sda.FillSchema(dt, SchemaType.Mapped); DataRow dr = dt.Rows.Find(textBox1.Text); dr["name"] = textBox2.Text; dr["gender"] = textBox4.Text; dr["money"] = textBox3.Text; dr["salary"] = textBox5.Text; //用于对数据集DataSet进行更改操作,同时作用于关联的数据库 SqlCommandBuilder scbd = new SqlCommandBuilder(sda); //更新DataTable中的数据 sda.Update(dt); //sda.Update(ds1, "oldDs"); }
原文地址:https://www.cnblogs.com/wby94510/p/9245505.html
时间: 2024-10-09 22:37:08