ASP.net:使用commond对象实现数据库的事务处理

实例:E:\study2\ASP.net\command8.3.1\command8.3.1.sln

 

 

protected void BtnAdd_Click(object sender, EventArgs e)
{
if (this.TextBox2.Text != "" && this.TextBox3.Text != "" && this.TextBox4.Text != "" && this.TextBox5.Text != "" && this.TextBox6.Text != "" && this.TextBox7.Text != "" && this.TextBox8.Text != "")
{
SqlConnection myConn = Getconnection();
myConn.Open();
// string sqlStr = "insert into tb_Student values('" + this.TextBox2.Text.Trim() +"','"+this.TextBox3.Text.Trim()+"','"+ this.TextBox4.Text.Trim() + "','" + this.TextBox5.Text.Trim() + "','" + this.TextBox6.Text.Trim() + "','" + this.TextBox7.Text.Trim()+ "','"+ this.TextBox8.Text.Trim() + "')";
// SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
SqlTransaction sqlTrans = myConn.BeginTransaction();
SqlCommand myCmd = new SqlCommand("insertStudent", myConn);
myCmd.Transaction = sqlTrans;
myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Parameters.Add("@Name", SqlDbType.NChar, 10).Value = this.TextBox2.Text.Trim();
myCmd.Parameters.Add(new SqlParameter("@PWD", this.TextBox3.Text.Trim())); //另一种方法实现语句
//myCmd.Parameters.Add("@PWD", SqlDbType.NChar, 10).Value = this.TextBox3.Text.Trim();
myCmd.Parameters.Add("@Sex", SqlDbType.NChar, 10).Value = this.TextBox4.Text.Trim();
myCmd.Parameters.Add("@JoinTime", SqlDbType.DateTime2, 7).Value = this.TextBox5.Text.Trim();
myCmd.Parameters.Add("@Question", SqlDbType.NVarChar, 50).Value = this.TextBox6.Text.Trim();
myCmd.Parameters.Add("@Answer", SqlDbType.NVarChar, 50).Value = this.TextBox7.Text.Trim();
myCmd.Parameters.Add("@Profession", SqlDbType.NChar, 10).Value = this.TextBox8.Text.Trim();

try
{
myCmd.ExecuteNonQuery();
sqlTrans.Commit();
myConn.Close();
this.Bind();
this.Scalar();
}
catch
{
Response.Write("<script>alert('插入失败,执行事务回滚!')</script>");
sqlTrans.Rollback(); //执行事务回滚
}

上一篇:ASP动态网页设计与Ajax技术-----打字机效果


下一篇:去除数组空格 php