日期:2014-05-18  浏览次数:21404 次

更新失败,失败原因:SqlConnection 不支持并行事务。
protected void Button2_Click(object sender, EventArgs e)
  {
  //连接字串"SqlConnString" 写到配置文件(web.config)中
  SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connkeji"].ConnectionString);
  conn.Open();
  SqlTransaction tran = null;
  try
  {
   

  for (int i = 0; i < GridView2.Rows.Count; i++)
  {
  string sqlStr = "";
  SqlCommand comm = new SqlCommand();
  tran = conn.BeginTransaction();

  string strname = GridView2.Rows[i].Cells[0].Text.Trim().ToString();
  string strpassword = GridView2.Rows[i].Cells[1].Text.Trim().ToString();
  string strqq = GridView2.Rows[i].Cells[2].Text.Trim().ToString();
  string stremail = GridView2.Rows[i].Cells[3].Text.Trim().ToString();
  string strphone = GridView2.Rows[i].Cells[4].Text.Trim().ToString();

  sqlStr += "INSERT my_user(user_name,user_password,user_qq,user_email,user_phone) VALUES ('" + strname + "','" + strpassword + "','" + strqq + "','" + stremail + "','"+strphone+"');";

   
  comm.CommandText = sqlStr;
  comm.Connection = conn;
  comm.Transaction = tran;
  comm.ExecuteNonQuery();
  }

  }
  catch (Exception ex)
  {
  Response.Write("更新失败,失败原因:" + ex.Message);
  tran.Rollback(); //事务回滚
  }
  finally
  {
  conn.Close();
  }
  }

------解决方案--------------------
探讨
protected void Button2_Click(object sender, EventArgs e)
{
//连接字串"SqlConnString" 写到配置文件(web.config)中
SqlConnection conn = new SqlConnection(System.Configuration.Configuration……

------解决方案--------------------
你那个里,也没有事务的commit
参照:
C# code

        public int ExecuteNonQuery(List<string> strSQL)
        {
            int index = 0;
            CheckConnection();

            //SqlCommand com = new SqlCommand(strSQL, con);
            using (SqlCommand cmd = con.CreateCommand())
            {
                SqlTransaction tran = con.BeginTransaction();
                cmd.Transaction = tran;
                try
                {
                    foreach (string item in strSQL)
                    {
                        cmd.CommandText = item;
                        cmd.ExecuteNonQuery();

                    }

                    tran.Commit();//如果都成功那么提交事物

                }
                catch (Exception ex)
                {
                    index = -1;
                    //throw new Exception(ex.Message);
                    tran.Rollback();
                }

                //index = com.ExecuteNonQuery();
            }


            return index;
        }
        public void CheckConnection()
        {
            if (this.con.State == ConnectionState.Closed)
            {
                this.con.Open();
            }
        }

------解决方案--------------------
3楼说的对,没注意循环
------解决方案--------------------
探讨