在.net中的事务可以这样写
protected int ExecuteSQLTrans(Hashtable cmdTexts,CommandType cmdType,SqlParameter[] cmdParms)
{
SqlConnection sqlconn = new SqlConnection(ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
if (sqlconn.State != ConnectionState.Open)
sqlconn.Open();
SqlTransaction trans = sqlconn.BeginTransaction("myTrans");
sqlcomm.Connection = sqlconn;
if (trans != null)
sqlcomm.Transaction = trans;
sqlcomm.CommandType = cmdType;
try
{
sqlcomm.Parameters.AddRange(cmdParms);
for (int i = 0; i < cmdTexts.Count; i++)
{
sqlcomm.CommandText = cmdTexts[i].ToString();
sqlcomm.ExecuteNonQuery();
}
trans.Commit();
return 0;
}
catch (Exception ex)
{
trans.Rollback();
return 1;
}
finally
{
sqlcomm.Dispose();
sqlconn.Close();
sqlconn.Dispose();
}
}
也就是,一个trans执行多个sql语句可以使用同一个SqlParameter数组参数.这样可以方便我们写事务.
SqlParameter数组可以用null调用.