存储过程写法
use UserManage
ALTER PROC ADDUser
AS
BEGIN
begin tran adduser--开始事务
begin try
INSERT INTO USERINFO VALUES ('Root' ,'123' ,'FALSE' )
INSERT INTO USERBED VALUES ('1' ,@@IDENTITY )
commit tran;
end try
begin catch--当遇到错误时执行catch
rollback tran;
end catch
END
EXEC ADDUser--执行存储过程
C#写法
private void button1_Click (object sender, EventArgs e)//回滚
{
string strCon = "Data Source=.;Initial Catalog=UserManage;Integrated Security=True" ;
SqlConnection conn = new SqlConnection(strCon);
conn.Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction tran;
tran = conn.BeginTransaction();
cmd.Transaction = tran;
cmd.Connection = conn;
try
{
cmd.CommandText = "INSERT INTO USERINFO VALUES('Root','123','FALSE')" ;
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO USERBED VALUES('文字',@@IDENTITY)" ;
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
MessageBox.Show("插入数据有误,已回滚" );
}
finally
{
this .userBedTableAdapter.Fill(this .userManageDataSet8.UserBed);
this .userInfoTableAdapter.Fill(this .userManageDataSet7.UserInfo);
conn.Close();
}
}
数据库
--CREATE DATABASE UserManage
--use UserManage
--CREATE TABLE UserInfo
--(
-- UserID int primary key identity(1 ,1 ),
-- UserName nvarchar(20 ) not null,
-- UserPassword nvarchar(20 ) not null,
-- IsAllow BIT NOT NULL
--)
--CREATE TABLE UserBed
--(
-- RoomID int primary key identity(1 ,1 ),
-- BedID int not null,
-- UserID int not null
--)
SELECT * FROM UserInfo
SELECT * FROM UserBed
Truncate table userinfo
truncate table userbed