经过长时间学习ADO.NET,于是和大家分享一下关于ADO.NET SQLDataAdapter完成对数据库的删除修改和插入的案例分析,看完本文你肯定可以全面理解ADO.NET的强大之处,大家赶快来看看吧!
#T#本实验目标是要求编写一个应用程序,利用ADO.NET SQLDataAdapter对象实现可以添加、修改、删除学生基本信息的功能。数据库为school,共有六个表,该应用程序中只使用了表student。数据表student中可以先存放一部分数据,便于后面处理。数据库环境是SQL Server 2005。用鼠标双击各个Button控件,进入.cs文件编辑状态准备进行开发。代码ADO.NET SQLDataAdapter动态程序部分如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Data.SqlClient;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace WindowsApplication1
- {
- public partial class Form9 : Form
- {
- private SqlConnection mycon;
- private SqlDataAdapter myada;
- private SqlCommand mycomd;
- private SqlCommandBuilder mycbd;
- private DataSet myset;
- public Form9()
- {
- InitializeComponent();
- mycon = new SqlConnection("Data Source=LKJ\\SQLEXPRESS;Initial Catalog=school;Integrated Security=True");
- mycomd = new SqlCommand("select * from student",mycon);
- myada = new SqlDataAdapter();
- myada.SelectCommand = mycomd;
- mycbd = new SqlCommandBuilder(myada);
- myset = new DataSet();
- myada.TableMappings.Add("student","student");
- myada.TableMappings[0].ColumnMappings.Add("SNO", "学号");
- myada.TableMappings[0].ColumnMappings.Add("SNAME", "姓名");
- myada.TableMappings[0].ColumnMappings.Add("SEX", "性别");
- myada.TableMappings[0].ColumnMappings.Add("BIRTHDAY", "生日");
- myada.TableMappings[0].ColumnMappings.Add("CLASS", "班级");
- }
- /// <summary>
- /// 数据修改
- /// </summary>
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- //将更改的数据更新到数据表里
- myada.Update(myset.Tables["student"].GetChanges());
- MessageBox.Show("数据库修改成功","成功信息");
- //DataTable接受更改,以便为下一次更改作准备
- myset.Tables["student"].AcceptChanges();
- }
- catch (SqlException ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- /// <summary>
- /// 初始化数据
- /// </summary>
- private void Form9_Load(object sender, EventArgs e)
- {
- try
- {
- myada.Fill(myset, "student");
- }
- catch (SqlException ex)
- {
- MessageBox.Show(ex.ToString());
- }
- finally
- {
- mycon.Close();
- }
- dataGridView1.DataSource = myset.Tables["student"].DefaultView;
- }
- /// <summary>
- /// 数据删除
- /// </summary>
- private void button2_Click(object sender, EventArgs e)
- {
- if (MessageBox.Show("确定要删除当前行数据?", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
- {
- try
- {
- //从DataTable中删除当前选中的行
- myset.Tables[0].Rows[dataGridView1.CurrentRow.Index].Delete();
- //将更改的数据更新到数据表里
- myada.Update(myset.Tables[0].GetChanges());
- MessageBox.Show("数据删除成功!");
- //DataTable接受更改,以便为下一次更改作准备
- myset.Tables[0].AcceptChanges();
- }
- catch (SqlException ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- else
- {
- //取消对DataTable的更改
- myset.Tables[0].RejectChanges();
- }
- }
- }