用sqldataadapter更新Dataset時設置事務,出錯!
主要出現以下問題:
在DataGridView中修改數據後,點Button1進行更新,如果數據正確,可以更新。但當出過錯後(比如其中一列不能為空,但是輸入為空)再更改輸入信息,點Button1進行更新,此時數據不能正確更新。
代碼如下:
private string sqlconn = SqlHelper.ConnectionString;
SqlConnection conn;
SqlTransaction myTrans;
DataSet ds;
SqlDataAdapter sda;
SqlCommandBuilder cmd;
public frmTest()
{
InitializeComponent();
}
private void frmTest_Load(object sender, EventArgs e)
{
conn = new SqlConnection(sqlconn);
conn.Open();
sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("Select * From DataTableCollection", conn);
ds = new DataSet();
sda.Fill(ds, "DataTableCollection");
this.dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
cmd = new SqlCommandBuilder(sda);
myTrans = cmd.GetInsertCommand().Connection.BeginTransaction();
cmd.GetInsertCommand().Transaction = myTrans;
cmd.GetDeleteCommand().Transaction = myTrans;
cmd.GetUpdateCommand().Transaction = myTrans;
try
{
sda.Update(ds.Tables[0]);
myTrans.Commit();
MessageBox.Show("成功!");
}
catch(Exception ex)
{
myTrans.Rollback();
MessageBox.Show("失敗!"+ex.Message);
}
finally
{
conn.Close();
}
}
------解决方案--------------------C# code
myTrans = sda.SelectCommand().Connection.BeginTransaction();
sda.InsertCommand().Transaction = myTrans;
sda.DeleteCommand().Transaction = myTrans;
sda.UpdateCommand().Transaction = myTrans;
------解决方案--------------------
SqlDataAdapter,更新数据时,遇到错误,就会退出Update方法.
可以用SqlCommand一笔一笔更新,如果执意要用SqlDataAdapter,可选择更新前检查datagridview数据的有效性,检查无误后,再调用Update方法.