请教高手datatable循环写入数据库的事务操作
下面这个程序是把一个datatable里面的行,循环插入数据库中,如果某一行插入失败,那么就取消之前的所有插入,所以用到事务,但是我这段代码执行出错。,如果把3行事务操作的代码注释掉,就能执行,应该是事务用法不对,请教如何才能实现整个表插入结束后再提交事务?
错误提示:ExecuteNonQuery requires the command to have a transation when the connection assigned to the command is in a pengding local transation. the transation propery of the command has not been initialized.
private bool ImportFromTable(ref DataTable dt)
{
DBConn db = new DBConn();
SqlConnection con = db.CreateCon();
SqlCommand cmd = new SqlCommand("", con);
SqlTransaction st = null;
try
{
con.Open();
st = con.BeginTransaction();//开始事务
foreach(DataRow dr in dt.Rows)
{
cmd.CommandText = "p_SetItems";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.Add("@FItemClassID", SqlDbType.Int).Value = this.FItemClassID;
cmd.Parameters.Add("@FMemo", SqlDbType.VarChar).Value = dr[1].ToString().Trim();
cmd.ExecuteNonQuery();
cmd.CommandText = "p_uptParentID";
cmd.Parameters.Clear();
cmd.Parameters.Add("@FParentID", SqlDbType.VarChar).Value = "0";
cmd.Parameters.Add("@FItemClassID", SqlDbType.Int).Value = this.FItemClassID;
cmd.ExecuteNonQuery();
}
st.Commit();//整个table全部写完后提交事务
}
catch (System.Exception ex)
{
st.Rollback();//回滚事务
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
con.Close();
}
return true;
}