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;
}
{
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;
}