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;
}
但是没有用仍然一行插入,一行没有插入
解决方案 »
- .net framework 3.5 支持的操作系统
- 请教log4net中如何将level为DEBUG和ERROR的两级分开存在两个文件之中(使用同一个logger的前提)。
- winform应用程序转dll
- 如何确保socket套接字接收数据的完整性?
- 怎样把从数据库读出来的汉字,以ASCII写入文本文件中,默认每次都是unicode编码写入文件的,别人打开是乱码
- 在WEBFORM程序里,我想在DATAGRID里放一个模版列,里面放一个DROPDOWNLIST,里面的数据是从数据库里读取出来的状态值。。
- 一个ASP.net简单的菜鸟问题
- 请问鼠标放到button控件的事件怎么处理?
- 工具条上的一个checkbox
- 怎样截取字符串?
- 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
{
//此处不用写捕获异常后的回滚,隐性自动回滚
}
}