您的位置:首页 > 数据库

C#数据库事务

2015-11-03 15:55 381 查看
public Boolean ExecuteTransaction(string[] sqls)

{

const string connectionString = "*******";

using (OdbcConnection connection =

new OdbcConnection(connectionString))

{

OdbcCommand command = new OdbcCommand();

OdbcTransaction transaction = null;

// Set the Connection to the new OdbcConnection.

command.Connection = connection;

// Open the connection and execute the transaction.

try

{

connection.Open();

// Start a local transaction

transaction = connection.BeginTransaction();

// Assign transaction object for a pending local transaction.

command.Connection = connection;

command.Transaction = transaction;

foreach (string sql in sqls)

{

System.Console.WriteLine(sql);

command.CommandText = sql;

command.ExecuteNonQuery();

}

// Execute the commands.

//command.CommandText =

// "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";

//command.ExecuteNonQuery();

// Commit the transaction.

transaction.Commit();

Console.WriteLine("Both records are written to database.");

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

try

{

transaction.Rollback();//事务回滚

}

catch

{

// Do nothing here; transaction is not active.

}

return false;

}

}

return true;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: