更新失败,失败原因: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();
}
}
[解决办法]
[解决办法]
你那个里,也没有事务的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楼说的对,没注意循环
[解决办法]
[解决办法]
你到底想创建多少个失误(事务)?
一次执行只要一个事务,但是你把事务的创建过程放到循环里去了,也就是创建了很多事务,这样不出错就奇怪了,和并行不并行无关,你根本就不会用事务,还不如不要用。