111,098
社区成员




t_provinceDAL dal = new t_provinceDAL();
using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 10, 0)))
{
bool rt = false;
rt = dal.add("121113");
rt = dal.delete(11);
tran.Complete();
}
//t_provinceDAL
public bool add(string pname)
{
string strSql = "insert into t_province(pname) values(@pname);";
return DBHelperMySQL.ExecuteNonQuery(strSql, new MySqlParameter("@pname", pname)) > 0;
}
public bool delete(int id)
{
string strSql = "delete from t_province where id = " + id.ToString();
return DBHelperMySQL.ExecuteNonQuery(strSql) > 0;
}
//DBHelper
public static int ExecuteNonQuery(string commandText, params MySqlParameter[] commandParameters)
{
MySqlConnection connection = new MySqlConnection(connectionString);
// Create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, null, CommandType.Text, commandText, commandParameters, out mustCloseConnection);
// Finally, execute the command
int retval = cmd.ExecuteNonQuery();
// Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear();
return retval;
}
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType commandType, string cmdText, MySqlParameter[] cmdParms, out bool mustCloseConnection)
{
mustCloseConnection = false;
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (MySqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
public void CustomTransactionScope(DelegateTransaction delegateTransaction)
{
MySqlConnection conn = new MySqlConnection(this._connectionString);
conn.Open();
MySqlTransaction trans = conn.BeginTransaction();
try
{
delegateTransaction(trans);
trans.Commit();
conn.Dispose();
}
catch (Exception ex)
{
trans.Rollback();
conn.Dispose();
throw ex;
}
}