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利用GD库生成缩略图示例