c#实现数据库事务示例分享
using system;
using system.data.sqlclient;
namespace executesqltran
{
class program
{
class result<t>
{
public t data;
public string message;
public bool success;
public string stacktrace;
}
struct executeableunit
{
public string sql;
public sqlparameter[] param;
}
/// <summary>
/// 执行多条sql语句,实现数据库事务。
/// </summary>
/// <param name="sqlstringlist">sql语句的哈希表(key为sql语句,value是该语句的sqlparameter[])</param>
private static result<int> executesqltransaction(params executeableunit[] executeableunits)
{
using (sqlconnection connection = new sqlconnection(""))
{
connection.open();
sqlcommand command = connection.createcommand();
sqltransaction transaction = connection.begintransaction();
command.connection = connection;
command.transaction = transaction;
int result = 0;
try
{
foreach(executeableunit exeunit in executeableunits)
{
command.commandtext = exeunit.sql;
if(exeunit.param.getlength(1) > 0)
{
foreach(sqlparameter p in exeunit.param)
command.parameters.add(p);
}
result += command.executenonquery();
}
transaction.commit();
}
catch (exception ex)
{
// attempt to roll back the transaction.
try
{
transaction.rollback();
}
catch (exception ex2)
{
return new result<int>()
{
success = false, message = ex2.message, stacktrace = ex2.stacktrace
};
}
return new result<int>()
{
success = false, message = ex.message, stacktrace = ex.stacktrace
};
}
finally
{
// attempt to roll back the transaction.
try
{
connection.close();
}
catch (exception ex)
{
}
}
return new result<int>()
{
success = true, data = result
};
}
}
public static void main(string[] args)
{
}
}
}
上一篇: 简单实用的网站PHP缓存类实例_PHP