大家帮我看看我怎么错了,,急急急,,,在线等!!!!!
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(System.Int32));
dt.Columns.Add("val",typeof(System.Int32));
DataRow dr1 = dt.NewRow();
dr1["id"] = 1; dr1["val"]=111;
DataRow dr2 = dt.NewRow();
dr2["id"] = 2; dr2["val"]=222;
dt.Rows.Add(dr2);
string strCon = "Data Source=.;Initial Catalog=test;Integrated Security=True";
SqlConnection sqlCon = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlCon;
sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction(); //开始执行事务
try
{
foreach (DataRow dr in dt.Rows)
{
cmd.CommandText = "update tb_2 set val = @val where id = @id";
cmd.Parameters.Add("@id", SqlDbType.Int);
cmd.Parameters["@id"].Value = Convert.ToInt32(dr["id"].ToString());
cmd.Parameters.Add("@val", SqlDbType.Int);
cmd.Parameters["@val"].Value = Int32.Parse(dr["val"].ToString());
cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
trans.Rollback();
}
finally
{
sqlCon.Close();
trans.Dispose();
sqlCon.Dispose();
}
Console.Read();
}
提示:如果分配给命令的连接位于本地挂起事务中,ExecuteNonQuery 要求命令拥有事务。命令的 Transaction 属性尚未初始化
------解决方案--------------------
cmd 需要设置SqlTransaction
------解决方案--------------------
cmd.Transaction = trans;
------解决方案--------------------
写在SqlTransaction trans = sqlCon.BeginTransaction(); //开始执行事务后面
------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqltransaction(v=VS.80).aspx看msdn的例子
------解决方案--------------------
C# code
try
{
cmd.Transaction = trans; //设置事物
foreach (DataRow dr in dt.Rows)
{
cmd.CommandText = "update tb_2 set val = @val where id = @id";
cmd.Parameters.Add("@id", SqlDbType.Int);
cmd.Parameters["@id"].Value = Convert.ToInt32(dr["id"].ToString());
cmd.Parameters.Add("@val", SqlDbType.Int);
cmd.Parameters["@val"].Value = Int32.Parse(dr["val"].ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();//注意要清空参数
}
trans.Commit();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
trans.Rollback();
}
finally
{
sqlCon.Close();
trans.Dispose();
sqlCon.Dispose();
}