数据库事务处理问题

akiy 2006-12-04 09:21:52
在vb里
on error resume next
conn.begintrans....
写表一....
写表二....
if err.number > 1 then
msgbox"写数据库失败!"
conn.rollback...
else
mesgbox"成功!"
conn.commit.....
end if
在C#里怎么代替??
...全文
110 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lingbo_wx 2006-12-04
  • 打赏
  • 举报
回复
up
zerg318 2006-12-04
  • 打赏
  • 举报
回复
收藏
akiy 2006-12-04
  • 打赏
  • 举报
回复
这点设计的不如VB方便。
jijl2001 2006-12-04
  • 打赏
  • 举报
回复
using (SqlConnection connection = new SqlConnection(connectString))
{
connection.Open();

// Start a local transaction.
SqlTransaction sqlTran = connection.BeginTransaction();

// Enlist the command in the current transaction.
SqlCommand command = connection.CreateCommand();
command.Transaction = sqlTran;

try
{
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
command.ExecuteNonQuery();
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
command.ExecuteNonQuery();
sqlTran.Commit();
Console.WriteLine("Both records were written to database.");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Neither record was written to database.");
sqlTran.Rollback();
}
}

51Crack 2006-12-04
  • 打赏
  • 举报
回复
//事务交给cmd了
SqlTransaction ta;
SqlCommand cmd=new SqlCommand;

try
{
conn.Open();
ta=conn.BeginTransaction();
cmd.Transaction = ta;
//你的操作
ta.Commit();
cmd.Dispose();
conn.Close();
}

110,552

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧