using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 数据适配器DataAdapter//断开式类型
{
public partial class Form1 : Form
{
SqlDataAdapter ad;
DataSet ds;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“myDBDataSet.student”中。您可以根据需要移动或删除它。
this.studentTableAdapter.Fill(this.myDBDataSet.student);
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=DESKTOP-UJ5IEQK\THIRTEEN;Initial Catalog=myDB;Integrated Security=true";
SqlCommand com = new SqlCommand("select * from course",con);
ad = new SqlDataAdapter();
ad.SelectCommand = com;
ad.RowUpdating += Ad_RowUpdating;//添加RowUpdating事件,数据更新之前跳出
ad.RowUpdated += Ad_RowUpdated;//添加RowUpdated事件,数据更新完成后跳出
SqlCommandBuilder cb = new SqlCommandBuilder(ad);//数据命令生成器对象
ds = new DataSet();
//1.自动打开连接,不需要写Open();
//2.执行完之后,自动关闭连接
//3.断开连接的数据访问方式
//4.先执行查询,填充数据集。数据集的结构和select语句相关
ad.Fill(ds);
dataGridView2.DataSource = ds.Tables[0];
}
private void Ad_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
//throw new NotImplementedException();
MessageBox.Show("Beginning Update...");
}
private void Ad_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
//throw new NotImplementedException();
MessageBox.Show("Update Completed");
}
private void button2_Click(object sender, EventArgs e)
{
try
{
ad.Update(ds);
}
catch
{
//在断开式应用程序中更新数据是,会发成并发性错误,下面是解决方法之一
if (ds.HasErrors)//测试HasEnors属性
{
foreach (DataTable table in ds.Tables)//检查每个表
{
if (table.HasErrors)
{
foreach (DataRow row in table.Rows)
{
if (row.HasErrors)
{
MessageBox.Show("Row:"+row[0],row.RowError);
foreach (DataColumn col in row.GetColumnsInError())//检查表的列
{
MessageBox.Show("Error in this column");
}
row.ClearErrors();//清除错误状态
row.RejectChanges();//拒绝每行的冲突数据
}
}
}
}
}
}
}
}
}
数据适配器DataAdapter
最新推荐文章于 2024-04-14 17:50:40 发布