您的位置:首页 > 其它

事务处理之连续插入中获取操作1中自动生成的key,用于操作2中的外键

2010-03-15 21:52 405 查看














事务处理过程:

登记人员及其毕业学校,若学校已经存在,则只添加人员,若学校不存在,则添加学校并添加人员

DB:School:sid,name;

People:pid,name,school
(foreign key with school:sid)



在一个事务处理中,插入学校后,利用@@IDENTITY,获取最近一个得标识值,赋给一个临时变量,然后再进行人员的插入

添加按钮事件处理过程:
if (txtSchool.Text == "")
{
using (SqlConnection con = new SqlConnection(CMD.DBHelper.connectionString))
{
try
{
con.Open();
SqlCommand comm = new SqlCommand("insert into test_worker(name,school) values('" +
txtName.Text + "',"+ddlSchool.SelectedValue+")", con);
int effectedrow = comm.ExecuteNonQuery();
if (effectedrow == 1)
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('添加成功');", true);
else
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('添加失败');", true);
}
finally
{
con.Close();
}
}
}
else
{
using (SqlConnection conn = new SqlConnection(CMD.DBHelper.connectionString))
{
conn.Open();
SqlTransaction myTrans = conn.BeginTransaction();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = conn;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "insert into test_school(name) values('" + txtSchool.Text +
"');select @@IDENTITY;";
int newId = int.Parse(myCommand.ExecuteScalar().ToString());
myCommand.CommandText = "insert into test_worker(name,school) values('" +
txtName.Text + "'," + newId + ")";
myCommand.ExecuteNonQuery();
myTrans.Commit();
}
catch (Exception ex)
{
myTrans.Rollback();
ClientScript.RegisterStartupScript(this.GetType(),"", "alert('添加失败');",true);
}
finally
{
conn.Close();
}
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('添加成功');", true);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐