亲宝软件园·资讯

展开

asp.net 事务 asp.net 使用事务

人气:0
想了解asp.net 使用事务的相关内容吗,在本文为您仔细讲解asp.net 事务的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:asp.net,事务,下面大家一起来学习吧。
ASP.NET操作事务非常的简单,代码如下:
代码
复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
public partial class swstudy : System.Web.UI.Page
{
private SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
}
private SqlConnection GetConnection()
{
if (conn!=null&&conn.State == ConnectionState.Open)
{
return conn;
}
else
{
return conn= new SqlConnection("server=PC-200911131211;database=test;uid=sa;pwd=sa123456");
}
}
//提交
protected void Button1_Click(object sender, EventArgs e)
{
string str1 = this.TextBox1.Text;
string str2 = this.TextBox2.Text;
using (GetConnection())
{
conn.Open();
//事务
SqlTransaction tran;
tran = conn.BeginTransaction();
//提交一
SqlCommand cmd1 = new SqlCommand("insert into m1(m1,m2)values('" + str1 + "','" + str2 + "')", conn);
cmd1.Transaction = tran;
//提交二
SqlCommand cmd2 = new SqlCommand("insert into messages(msg)values('" + str1 + "')", conn);
cmd2.Transaction = tran;
try
{
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
tran.Commit();//提交事物
Response.Write("<script>alert('全部提交OK')</script>");
}
catch
{
tran.Rollback();//回滚操作
Response.Write("<script>alert('事务回滚')</script>");
}
finally
{
conn.Close();
}
}
}
}

加载全部内容

相关教程
猜你喜欢
用户评论