SQL 事務 (存儲過程與事務)
來源:程序員人生 發(fā)布時間:2015-01-20 08:25:14 閱讀次數:3712次
<1>
C# 履行SQL事務 又兩種方法(本人總結的)
1.通過存儲進程。 現在就演示1下通過存儲進程來履行SQL事務。
2.通過C#中提供的 Transaction 。
SQL Server 事務語法
Sql server 事務的兩種用法
<1>創(chuàng)建1個存儲進程,
use sales --指定
數據庫
create table bb --創(chuàng)建bb 這個表
(
ID int not null primary key ,--賬號
Moneys money --轉賬金額
)
--bb表里插入兩條數據
insert into bb values('1',2000) --賬戶 1 里有2000元
insert into bb values('2',3000) --賬戶 2 里有3000元
go
if(exists(select * from sys.objects where name='proc_bb')) --如果存儲這條存儲進程存在則先刪除
drop proc Proc_bb
go
create proc Proc_bb --創(chuàng)建名字為Proc_bb的存儲進程 帶3個參數
(
@fromID int, --轉出賬戶
@toID int, --接收轉賬的賬戶
@momeys money --轉賬金額
)
as
begin tran --開始履行事務
update bb set Moneys=Moneys-@momeys where ID=@fromID ---履行的第1個操作,轉賬 原來的金額-轉賬的金額
update bb set Moneys=Moneys+@momeys where ID=@toID --履行第2個操作,接受轉賬 原來的的金額+轉賬的金額
if @@ERROR<>0 --判斷 如果兩條語句有任何1條出現毛病。(如果前面的SQL 語句履行沒有毛病,則返回0)
begin
rollback tran --開始履行事務的回滾,恢復轉賬開始之前的狀態(tài)
return 0
end
else --如果兩個語句都履行成功
begin
commit tran --履行這個事務的操作
end
go
exec Proc_bb 1,2 ,2000 --履行這條存儲進程; 轉賬賬戶為 1 接收賬戶為 2 轉賬的金額為 2000元
在C#中履行上面這個存儲進程
WebForm2.aspx.cs頁面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
namespace 用戶激活
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connStr=ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//SqlParameter sqlParameter=new SqlParameter();
SqlParameter [] sqlParameters={
new SqlParameter("@toID",ToID.Text.Trim()),
new SqlParameter("fromID",FromID.Text.Trim()),
new SqlParameter("@money",Money.Text.Trim())
};
cmd.CommandText = "exec Proc_bb @toID, @fromID, @money";
cmd.Parameters.AddRange(sqlParameters);
int i= cmd.ExecuteNonQuery();
if (i > 0)
{
Msg.Text = "轉賬成功";
}
else
{
Msg.Text = "轉賬失敗";
}
}
}
}
}
}
WebForm2.aspx頁面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="用戶激活.WebForm2" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
轉賬賬戶:<asp:TextBox ID="ToID" runat="server"></asp:TextBox></br>
接收賬戶:<asp:TextBox ID="FromID" runat="server"></asp:TextBox></br>
轉賬金額:<asp:TextBox ID="Money" runat="server"></asp:TextBox></br>
轉賬是不是成功:<asp:Label ID="Msg" runat="server" Text=""></asp:Label></br>
<asp:Button ID="Button1" runat="server" Text="提交轉賬" onclick="Button1_Click" />
</form>
</body>
</html>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈