大家好,又见面了,我是你们的朋友全栈君。
下面的示例创建一个 SqlConnection 和一个 SqlTransaction。此示例还演示如何使用 BeginTransaction、Commit 和 Rollback 等方法。出现任何错误时事务都会回滚。Try/Catch 错误处理用于处理尝试提交或回滚事务时的所有错误。
System;
using
System.Configuration;
using
System.Data.SqlClient;
using
System.Transactions;
protected
void
Page_Load(
object
sender, EventArgs e)
{
using
(SqlConnection conn
=
new
SqlConnection(ConfigurationManager.ConnectionStrings[
“
ConnStr
“
].ToString()))
{
conn.Open();
SqlTransaction _transaction
=
conn.BeginTransaction();
try
{
SqlCommand _cmd
=
new
SqlCommand(
“
Insert Into T_Test(F_Name) values(@Name)
“
,conn);
_cmd.Parameters.Add(
new
SqlParameter(
“
@Name
“
,
“
Test1
“
));
_cmd.Transaction
=
_transaction;
_cmd.ExecuteNonQuery();
_cmd.Parameters.Clear();
_cmd.Parameters.Add(
new
SqlParameter(
“
@Name
“
,
“
Test2
“
+
new
String(
‘
2
‘
,
100
)));
_cmd.ExecuteNonQuery();
//
F_Name为Nvarchar(50),这里会报错
_transaction.Commit();
Response.Write(
“
二条记录已经成功入库!
“
);
}
catch
(Exception ex)
{
Response.Write(
“
发生错误:
“
+
ex.Message.ToString());
try
{
_transaction.Rollback();
Response.Write(
“
<br/>事务已成功回滚!
“
);
}
catch
(Exception ex2)
{
Response.Write(
“
<br/>回滚失败:
“
+
ex2.Message.ToString());
}
}
_transaction.Dispose();
}
}
如果换成时下流行的Linq To Sql写法,大致如下:
(DataContext context
=
new
DataContext(connStr))
{
SqlConnection conn
=
new
SqlConnection();
if
(context.Connection
!=
null
&&
context.Connection.State
!=
ConnectionState.Open) context.Connection.Open();
context.Transaction
=
context.Connection.BeginTransaction();
try
{
User user
=
new
User();
user.Name
=
“
aaaa
“
;
users.Add(user);
context.SubmitChanges();
users.Remove(users.Single(u
=>
u.Name
==
“
aaaa
“
));
context.SubmitChanges();
context.Transaction.Commit();
}
catch
{
try
{
context.Transaction.Rollback();
}
catch
{
//
}
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/142705.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...