datagridview 有两行数据,一行正确,一行错误,用SqlDataAdapter.update(table) 插入数据,
一行插入,一行没有插入,有什么方法让两行数据都不能插入,或者插入的一行回滚?
我已经用了事物如下:
SqlTransaction tx = con.BeginTransaction();
apdate.UpdateCommand = new SqlCommand();
apdate.UpdateCommand.Transaction = tx;
try
{
apdate.Update(tabl);
}
catch
{
MessageBox.Show("运行错误");
tx.Rollback();
return;
}
但是没有用仍然一行插入,一行没有插入
解决方案 »
- 问个循环密码,我自己想半天只能嵌套26*2+10个循环嵌套,太可怕了
- C# 画直线带一个箭头 完成了大部分
- 怎样让这个无限循环停下来?(在线等答复)
- 赐教:为何不能再命令行中输入参数?
- CSS设置字体好奇怪的问题 有经验的人来帮忙看下!
- 也就是说可以在我们自己的WEB页面中有个象EXCEL或WORD的一样的编辑器
- asp.net应用程序 cache 、static 变量 线程安全问题?
- SOCKET的问题!!!急
- 问大家一个问题(素数)!!!
- 我编程生成的xls文件里面的数字变成文本,怎么才能变成数字啊?这样在一打开Excel时,就可以对里面的数字求和等。
- UTF-8文本文档EXCEL打开的一些问题
- C#有没有什么比较好用的辅助工具
datagridview 的两行数据
在同一个事务里面
一次性插入
在同一个事务里面
string sqlstr = "select xsid,spid,spjm,spmc,sptm,spgg,xssl,ddw,xxssl,xdw,xsdj,xsje,xsrq,";
sqlstr += "ckid,ckmc,xsph,hsdw,ps,bz,khid,khmc,gsid,czyid,xshs,che,xsdh from spxs where xsph='" + txtph.Text + "'";
cmd = new SqlCommand(sqlstr, new SqlConnection(Coon.getcoon()));
apdate = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(apdate);
apdate.Fill(tabl);
datagridview.DataSource = tabl;
插入数据: SqlTransaction tx = con.BeginTransaction();
apdate.UpdateCommand = new SqlCommand();
apdate.UpdateCommand.Transaction = tx;
try
{
apdate.Update(tabl);
}
catch
{
MessageBox.Show("运行错误");
tx.Rollback();
return;
}
apdate.UpdateCommand = new SqlCommand();
apdate.UpdateCommand.Transaction = tx;
try
{
//正确数据操作的SQL命令
apdate.Update(tabl);
//错误数据操作的SQL命令
apdate.Update(tabl);
tx.Commit();
}
catch
{
MessageBox.Show("运行错误");
tx.Rollback();
return;
}
apdate.UpdateCommand.Transaction = tx; 这句话是没有用的,只写apdate.UpdateCommand.Transaction = tx;
apdate.UpdateCommand是会自动生成的!
apdate.UpdateCommand = new SqlCommand();
未将对象引用设置到对象的实例。
string sqlstr = "select xsid,spid,spjm,spmc,sptm,spgg,xssl,ddw,xxssl,xdw,xsdj,xsje,xsrq,";
sqlstr += "ckid,ckmc,xsph,hsdw,ps,bz,khid,khmc,gsid,czyid,xshs,che,xsdh from spxs where xsph='" + txtph.Text + "'";
cmd = new SqlCommand(sqlstr, new SqlConnection(Coon.getcoon()));
apdate = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(apdate);
apdate.Fill(tabl);
datagridview.DataSource = tabl;
插入数据: SqlTransaction tx = con.BeginTransaction();
apdate.UpdateCommand = new SqlCommand();
apdate.UpdateCommand.Transaction = tx;
try
{
apdate.Update(tabl);
tx.Commit();
}
catch
{
MessageBox.Show("运行错误");
tx.Rollback();
return;
}
using(TransactionScope tran = new TransactionScope())
{
try
{ }
catch
{
//此处不用写捕获异常后的回滚,隐性自动回滚
}
}
光看你这句就有问题,怎么创建了一个没有任何SQL语句的更新命令?而且还没有设置数据库连接,这能正常执行才怪。
using(TransactionScope tran = new TransactionScope())
{
try
{
..........
tran.Complete();//放在操作段结尾指示事务已完成,如果发生异常,这个不会被调用并且自动回滚
}
catch
{
//此处不用写捕获异常后的回滚,隐性自动回滚
}
}