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;
}
{
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;
}
相关文章推荐
- redis--------安装
- Redis数据备份与恢复
- 【转】去掉Sqlite3 数据库中的前后回车换行符(newline)
- Mysql Merge表的使用注意事项和优点介绍
- python3怎么连接mongodb?
- sqlite3 语句总结
- mysql 分割字符添加入多个字段
- oracle数据库ORA-00600:internalerrorcode,arguments:[keltnfy-ldmInit],[46],[1],[],[],[],[],[])
- [转]Creating Mailing Labels in SQL Server Reporting Services (rdlc 数据1页 2竖排 显示)
- PD使用心得1
- Rsyslog+MySQL+LogAnalyzer部署日志服务器
- SQL中MAX()和MIN()函数的使用
- PLSQL 的 for循环的小例子
- SQL 通配符
- TA+3框架配置多个数据库链接
- redis 存取键值对常用的三种使用方式 - Jedis、JedisPool、Jedis分布式
- [MySQL FAQ]系列 — 打开general log到底影响多大
- No9 SQLite
- sql语句获取本周、上一周、本月数据
- 性能测试中SQL引起的性能问题