原理:需要开启事务的Action贴上Transaction标签,则Action执行前开启事务,Action执行完提交事务,如果Action报错,则回滚事务。

OracleHelper代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml.Linq;
using System.Data.Objects.DataClasses;
using Models; namespace DBHelper
{
/// <summary>
/// Oracle操作类
/// 2015年6月20日
/// 写程序之前,首先引用System.Data.OracleClient
/// </summary>
public class OracleHelper
{
#region 静态变量
/// <summary>
/// 数据库连接字符串
/// </summary>
private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
#endregion #region OracleConnection 获取数据库连接
/// <summary>
/// 获取数据库连接
/// </summary>
private static OracleConnection GetConn()
{
OracleConnection connection = null; string key = "Simpo2016_OracleConnection"; if (HttpContext.Current.Items[key] == null)
{
connection = new OracleConnection(connectionString);
connection.Open();
HttpContext.Current.Items[key] = connection;
}
else
{
connection = (OracleConnection)HttpContext.Current.Items[key];
} return connection;
}
#endregion #region OracleTransaction 获取事务对象
/// <summary>
/// 获取事务对象
/// </summary>
private static OracleTransaction GetTran()
{
OracleTransaction tran = null; string key = "Simpo2016_OracleTransaction"; if (HttpContext.Current.Items[key] == null)
{
tran = GetConn().BeginTransaction();
HttpContext.Current.Items[key] = tran;
}
else
{
tran = (OracleTransaction)HttpContext.Current.Items[key];
} return tran;
}
#endregion #region 开起事务标志
/// <summary>
/// 事务标志
/// </summary>
private static string tranFlagKey = "Simpo2016_OracleTransaction_Flag";
/// <summary>
/// 添加事务标志
/// </summary>
public static void AddTranFlag()
{
HttpContext.Current.Items[tranFlagKey] = true;
}
/// <summary>
/// 移除事务标志
/// </summary>
public static void RemoveTranFlag()
{
HttpContext.Current.Items[tranFlagKey] = false;
}
/// <summary>
/// 事务标志
/// </summary>
public static bool TranFlag
{
get
{
bool tranFlag = false; if (HttpContext.Current.Items[tranFlagKey] != null)
{
tranFlag = (bool)HttpContext.Current.Items[tranFlagKey];
} return tranFlag;
}
}
#endregion #region 用于查询的数据库连接
/// <summary>
/// 用于查询的数据库连接
/// </summary>
private OracleConnection m_Conn;
#endregion #region 构造函数
public OracleHelper()
{
m_Conn = new OracleConnection(connectionString);
}
#endregion #region 基础方法
#region 执行简单SQL语句
#region Exists
public bool Exists(string sqlString)
{
using (OracleCommand cmd = new OracleCommand(sqlString, m_Conn))
{
try
{
m_Conn.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
m_Conn.Close();
}
}
}
#endregion #region 执行SQL语句,返回影响的记录数
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string sqlString)
{
OracleConnection connection = GetConn();
using (OracleCommand cmd = new OracleCommand(sqlString, connection))
{
try
{
if (connection.State != ConnectionState.Open) connection.Open();
if (TranFlag) cmd.Transaction = GetTran();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
cmd.Dispose();
if (!TranFlag) connection.Close();
}
}
}
#endregion #region 执行一条计算查询结果语句,返回查询结果
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)
/// </summary>
/// <param name="sqlString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string sqlString)
{
using (OracleCommand cmd = new OracleCommand(sqlString, m_Conn))
{
try
{
m_Conn.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
m_Conn.Close();
}
}
}
#endregion #region 执行查询语句,返回SQLiteDataReader
/// <summary>
/// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public OracleDataReader ExecuteReader(string sqlString)
{
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand cmd = new OracleCommand(sqlString, connection);
try
{
connection.Open();
OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region 执行查询语句,返回DataSet
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OracleDataAdapter command = new OracleDataAdapter(sqlString, connection);
command.Fill(ds, "ds");
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
return ds;
}
}
#endregion
#endregion #region 执行带参数的SQL语句
#region 执行SQL语句,返回影响的记录数
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql(string SQLString, params OracleParameter[] cmdParms)
{
OracleConnection connection = GetConn();
using (OracleCommand cmd = new OracleCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
if (TranFlag) cmd.Transaction = GetTran();
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
if (!TranFlag) connection.Close();
}
}
}
#endregion #region 执行查询语句,返回SQLiteDataReader
/// <summary>
/// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public OracleDataReader ExecuteReader(string sqlString, params OracleParameter[] cmdParms)
{
OracleCommand cmd = new OracleCommand();
try
{
PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region 执行查询语句,返回DataSet
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns>DataSet</returns>
public DataSet Query(string sqlString, params OracleParameter[] cmdParms)
{
OracleCommand cmd = new OracleCommand();
PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
m_Conn.Close();
}
return ds;
}
}
#endregion #region PrepareCommand
private void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open) conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null) cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
if (cmdParms != null)
{
foreach (OracleParameter parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}
}
#endregion
#endregion
#endregion #region 增删改查
#region 获取最大编号
/// <summary>
/// 获取最大编号
/// </summary>
/// <typeparam name="T">实体Model</typeparam>
/// <param name="key">主键</param>
public int GetMaxID<T>(string key)
{
Type type = typeof(T); string sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
using (OracleCommand cmd = new OracleCommand(sql, m_Conn))
{
try
{
m_Conn.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return ;
}
else
{
return int.Parse(obj.ToString()) + ;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
m_Conn.Close();
}
}
}
#endregion #region 添加
/// <summary>
/// 添加
/// </summary>
public void Insert(object obj)
{
StringBuilder strSql = new StringBuilder();
Type type = obj.GetType();
strSql.Append(string.Format("insert into {0}(", type.Name)); PropertyInfo[] propertyInfoList = GetEntityProperties(type);
List<string> propertyNameList = new List<string>();
foreach (PropertyInfo propertyInfo in propertyInfoList)
{
propertyNameList.Add(propertyInfo.Name);
} strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => ":" + a).ToArray())));
OracleParameter[] parameters = new OracleParameter[propertyInfoList.Length];
for (int i = ; i < propertyInfoList.Length; i++)
{
PropertyInfo propertyInfo = propertyInfoList[i];
object val = propertyInfo.GetValue(obj, null);
OracleParameter oracleParameter = new OracleParameter(":" + propertyInfo.Name, val == null ? DBNull.Value : val);
parameters[i] = oracleParameter;
} ExecuteSql(strSql.ToString(), parameters);
}
#endregion #region 修改
/// <summary>
/// 修改
/// </summary>
public void Update(object obj)
{
object oldObj = Find(obj);
if (oldObj == null) throw new Exception("无法获取到旧数据"); StringBuilder strSql = new StringBuilder();
Type type = obj.GetType();
strSql.Append(string.Format("update {0} ", type.Name)); PropertyInfo[] propertyInfoList = GetEntityProperties(type);
List<string> propertyNameList = new List<string>();
int savedCount = ;
foreach (PropertyInfo propertyInfo in propertyInfoList)
{
object oldVal = propertyInfo.GetValue(oldObj, null);
object val = propertyInfo.GetValue(obj, null);
if (!object.Equals(oldVal, val))
{
propertyNameList.Add(propertyInfo.Name);
savedCount++;
}
} strSql.Append(string.Format(" set "));
OracleParameter[] parameters = new OracleParameter[savedCount];
StringBuilder sbPros = new StringBuilder();
int k = ;
for (int i = ; i < propertyInfoList.Length; i++)
{
PropertyInfo propertyInfo = propertyInfoList[i];
object oldVal = propertyInfo.GetValue(oldObj, null);
object val = propertyInfo.GetValue(obj, null);
if (!object.Equals(oldVal, val))
{
sbPros.Append(string.Format(" {0}=:{0},", propertyInfo.Name));
OracleParameter oracleParameter = new OracleParameter(":" + propertyInfo.Name, val == null ? DBNull.Value : val);
parameters[k++] = oracleParameter;
}
}
if (sbPros.Length > )
{
strSql.Append(sbPros.ToString(, sbPros.Length - ));
}
strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString())); if (savedCount > )
{
ExecuteSql(strSql.ToString(), parameters);
}
}
#endregion #region 删除
/// <summary>
/// 根据Id删除
/// </summary>
public void Delete<T>(int id)
{
Type type = typeof(T);
StringBuilder sbSql = new StringBuilder();
sbSql.Append(string.Format("delete from {0} where {2}='{1}'", type.Name, id, GetIdName(type))); ExecuteSql(sbSql.ToString());
}
/// <summary>
/// 根据Id集合删除
/// </summary>
public void BatchDelete<T>(string ids)
{
if (string.IsNullOrWhiteSpace(ids)) return; Type type = typeof(T);
StringBuilder sbSql = new StringBuilder();
sbSql.Append(string.Format("delete from {0} where {2} in ({1})", type.Name, ids, GetIdName(type))); ExecuteSql(sbSql.ToString());
}
/// <summary>
/// 根据条件删除
/// </summary>
public void Delete<T>(string conditions)
{
if (string.IsNullOrWhiteSpace(conditions)) return; Type type = typeof(T);
StringBuilder sbSql = new StringBuilder();
sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions)); ExecuteSql(sbSql.ToString());
}
#endregion #region 获取实体
#region 根据实体获取实体
/// <summary>
/// 根据实体获取实体
/// </summary>
private object Find(object obj)
{
Type type = obj.GetType(); object result = Activator.CreateInstance(type);
bool hasValue = false;
IDataReader rd = null; string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType())); try
{
rd = ExecuteReader(sql); PropertyInfo[] propertyInfoList = GetEntityProperties(type); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
hasValue = true;
IDataRecord record = rd; foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} if (hasValue)
{
return result;
}
else
{
return null;
}
}
#endregion #region 根据Id获取实体
/// <summary>
/// 根据Id获取实体
/// </summary>
private object FindById(Type type, int id)
{
object result = Activator.CreateInstance(type);
IDataReader rd = null;
bool hasValue = false; string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type)); try
{
rd = ExecuteReader(sql); PropertyInfo[] propertyInfoList = GetEntityProperties(type); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
hasValue = true;
IDataRecord record = rd; foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} if (hasValue)
{
return result;
}
else
{
return null;
}
}
#endregion #region 根据Id获取实体
/// <summary>
/// 根据Id获取实体
/// </summary>
public T FindById<T>(string id) where T : new()
{
Type type = typeof(T);
T result = (T)Activator.CreateInstance(type);
IDataReader rd = null;
bool hasValue = false; string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type)); try
{
rd = ExecuteReader(sql); PropertyInfo[] propertyInfoList = GetEntityProperties(type); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
hasValue = true;
IDataRecord record = rd; foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} if (hasValue)
{
return result;
}
else
{
return default(T);
}
}
#endregion #region 根据sql获取实体
/// <summary>
/// 根据sql获取实体
/// </summary>
public T FindBySql<T>(string sql) where T : new()
{
Type type = typeof(T);
T result = (T)Activator.CreateInstance(type);
IDataReader rd = null;
bool hasValue = false; try
{
rd = ExecuteReader(sql); PropertyInfo[] propertyInfoList = GetEntityProperties(type); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
hasValue = true;
IDataRecord record = rd; foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} if (hasValue)
{
return result;
}
else
{
return default(T);
}
}
#endregion
#endregion #region 获取列表
/// <summary>
/// 获取列表
/// </summary>
public List<T> FindListBySql<T>(string sql) where T : new()
{
List<T> list = new List<T>();
object obj;
IDataReader rd = null; try
{
rd = ExecuteReader(sql); if (typeof(T) == typeof(int))
{
while (rd.Read())
{
list.Add((T)rd[]);
}
}
else if (typeof(T) == typeof(string))
{
while (rd.Read())
{
list.Add((T)rd[]);
}
}
else
{
PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties(); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
IDataRecord record = rd;
obj = new T(); foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
list.Add((T)obj);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} return list;
}
#endregion #region 获取列表
/// <summary>
/// 获取列表
/// </summary>
public List<T> FindListBySql<T>(string sql, params OracleParameter[] cmdParms) where T : new()
{
List<T> list = new List<T>();
object obj;
IDataReader rd = null; try
{
rd = ExecuteReader(sql, cmdParms); if (typeof(T) == typeof(int))
{
while (rd.Read())
{
list.Add((T)rd[]);
}
}
else if (typeof(T) == typeof(string))
{
while (rd.Read())
{
list.Add((T)rd[]);
}
}
else
{
PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties(); int fcnt = rd.FieldCount;
List<string> fileds = new List<string>();
for (int i = ; i < fcnt; i++)
{
fileds.Add(rd.GetName(i).ToUpper());
} while (rd.Read())
{
IDataRecord record = rd;
obj = new T(); foreach (PropertyInfo pro in propertyInfoList)
{
if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
{
continue;
} pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
}
list.Add((T)obj);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rd != null && !rd.IsClosed)
{
rd.Close();
rd.Dispose();
}
} return list;
}
#endregion #region 分页获取列表
/// <summary>
/// 分页(任意entity,尽量少的字段)
/// </summary>
public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage) where T : new()
{
PagerModel pagerModel = new PagerModel(); using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
string commandText = string.Format("select count(*) from ({0}) T", sql);
IDbCommand cmd = new OracleCommand(commandText, connection);
pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString()); int startRow = pageSize * (currentPage - );
int endRow = startRow + pageSize; StringBuilder sb = new StringBuilder();
sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
sb.Append(sql);
if (!string.IsNullOrWhiteSpace(orderby))
{
sb.Append(" ");
sb.Append(orderby);
}
sb.Append(" ) row_limit where rownum <= ");
sb.Append(endRow);
sb.Append(" ) where rownum_ >");
sb.Append(startRow); List<T> list = FindListBySql<T>(sb.ToString());
pagerModel.result = list;
} return pagerModel;
}
#endregion #region 分页获取列表
/// <summary>
/// 分页(任意entity,尽量少的字段)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <returns></returns>
public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage, params OracleParameter[] cmdParms) where T : new()
{
PagerModel pagerModel = new PagerModel(); using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
string commandText = string.Format("select count(*) from ({0}) T", sql);
OracleCommand cmd = new OracleCommand(commandText, connection);
PrepareCommand(cmd, connection, null, commandText, cmdParms);
pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
cmd.Parameters.Clear(); int startRow = pageSize * (currentPage - );
int endRow = startRow + pageSize; StringBuilder sb = new StringBuilder();
sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
sb.Append(sql);
if (!string.IsNullOrWhiteSpace(orderby))
{
sb.Append(" ");
sb.Append(orderby);
}
sb.Append(" ) row_limit where rownum <= ");
sb.Append(endRow);
sb.Append(" ) where rownum_ >");
sb.Append(startRow); List<T> list = FindListBySql<T>(sb.ToString(), cmdParms);
pagerModel.result = list;
} return pagerModel;
} #endregion #region 分页获取列表
/// <summary>
/// 分页(任意entity,尽量少的字段)
/// </summary>
public DataSet FindPageBySql(string sql, string orderby, int pageSize, int currentPage, out int totalCount, params OracleParameter[] cmdParms)
{
DataSet ds = null; using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
string commandText = string.Format("select count(*) from ({0}) T", sql);
IDbCommand cmd = new OracleCommand(commandText, connection);
totalCount = int.Parse(cmd.ExecuteScalar().ToString()); int startRow = pageSize * (currentPage - );
int endRow = startRow + pageSize; StringBuilder sb = new StringBuilder();
sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
sb.Append(sql);
if (!string.IsNullOrWhiteSpace(orderby))
{
sb.Append(" ");
sb.Append(orderby);
}
sb.Append(" ) row_limit where rownum <= ");
sb.Append(endRow);
sb.Append(" ) where rownum_ >");
sb.Append(startRow); ds = Query(sql, cmdParms);
} return ds;
}
#endregion #region getReaderValue 转换数据
/// <summary>
/// 转换数据
/// </summary>
private Object getReaderValue(Object rdValue, Type ptype)
{
if (ptype == typeof(double))
return Convert.ToDouble(rdValue); if (ptype == typeof(decimal))
return Convert.ToDecimal(rdValue); if (ptype == typeof(int))
return Convert.ToInt32(rdValue); if (ptype == typeof(long))
return Convert.ToInt64(rdValue); if (ptype == typeof(DateTime))
return Convert.ToDateTime(rdValue); if (ptype == typeof(Nullable<double>))
return Convert.ToDouble(rdValue); if (ptype == typeof(Nullable<decimal>))
return Convert.ToDecimal(rdValue); if (ptype == typeof(Nullable<int>))
return Convert.ToInt32(rdValue); if (ptype == typeof(Nullable<long>))
return Convert.ToInt64(rdValue); if (ptype == typeof(Nullable<DateTime>))
return Convert.ToDateTime(rdValue); return rdValue;
}
#endregion #region 获取主键名称
/// <summary>
/// 获取主键名称
/// </summary>
public string GetIdName(Type type)
{
PropertyInfo[] propertyInfoList = GetEntityProperties(type);
foreach (PropertyInfo propertyInfo in propertyInfoList)
{
if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > )
{
return propertyInfo.Name;
}
}
return "Id";
}
#endregion #region 获取主键值
/// <summary>
/// 获取主键名称
/// </summary>
public object GetIdVal(object val)
{
string idName = GetIdName(val.GetType());
if (!string.IsNullOrWhiteSpace(idName))
{
return val.GetType().GetProperty(idName).GetValue(val, null);
}
return ;
}
#endregion #region 获取实体类属性
/// <summary>
/// 获取实体类属性
/// </summary>
private PropertyInfo[] GetEntityProperties(Type type)
{
List<PropertyInfo> result = new List<PropertyInfo>();
PropertyInfo[] propertyInfoList = type.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfoList)
{
if (propertyInfo.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Length ==
&& propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false).Length == )
{
result.Add(propertyInfo);
}
}
return result.ToArray();
}
#endregion
#endregion #region 事务
#region 开始事务
/// <summary>
/// 开始事务
/// </summary>
public static void BeginTransaction()
{
GetTran();
AddTranFlag();
}
#endregion #region 提交事务
/// <summary>
/// 提交事务
/// </summary>
public static void CommitTransaction()
{
try
{
if (GetConn().State == ConnectionState.Open)
{
GetTran().Commit();
RemoveTranFlag();
}
}
catch (Exception ex)
{
GetTran().Rollback();
RemoveTranFlag();
}
finally
{
if (GetConn().State == ConnectionState.Open) GetConn().Close();
}
}
#endregion #region 回滚事务(出错时调用该方法回滚)
/// <summary>
/// 回滚事务(出错时调用该方法回滚)
/// </summary>
public static void RollbackTransaction()
{
GetTran().Rollback();
RemoveTranFlag();
GetConn().Close();
}
#endregion
#endregion }
}

在MVC4项目的FilterConfig.cs文件中,添加ActionFilter拦截器:

using System.Web;
using System.Web.Mvc;
using Common; namespace TechReport.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ActionFilter());
}
}
}

ActionFilter拦截器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using DBHelper; namespace Common
{
/// <summary>
/// Action拦截器
/// </summary>
public class ActionFilter : FilterAttribute, IActionFilter
{
//在执行操作方法之前调用
public void OnActionExecuting(ActionExecutingContext filterContext)
{
MethodInfo method = filterContext.Controller.GetType().GetMethod(filterContext.ActionDescriptor.ActionName);
object[] transactionAttributes = method.GetCustomAttributes(typeof(TransactionAttribute), false);
if (transactionAttributes.Length > )
{
OracleHelper.BeginTransaction();
}
} //在执行操作方法后调用
public void OnActionExecuted(ActionExecutedContext filterContext)
{
MethodInfo method = filterContext.Controller.GetType().GetMethod(filterContext.ActionDescriptor.ActionName);
object[] transactionAttributes = method.GetCustomAttributes(typeof(TransactionAttribute), false);
if (transactionAttributes.Length > )
{
if (filterContext.Exception == null)
{
OracleHelper.CommitTransaction();
}
else
{
OracleHelper.RollbackTransaction();
filterContext.ExceptionHandled = true;
ContentResult contentResult = new ContentResult();
contentResult.Content = filterContext.Exception.Message;
filterContext.Result = contentResult;
}
}
}
}
}

TransactionAttribute类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Common
{
/// <summary>
/// 开启事务,添加此特性的方法不要使用try catch,若要使用,catch中应将错误再次抛出
/// </summary>
[Serializable, AttributeUsage(AttributeTargets.Method)]
public class TransactionAttribute : Attribute
{
}
}

在Action上添加[Transaction]标签:

[Transaction]
public ActionResult Submit(string reportCode)
{
string strParams = Request["params"];
REPORTAUDIT reportAudit = new REPORTAUDIT();
REPORTFLOW reportFlow = new REPORTFLOW(); SYS_USER empdetail = m_UserDal.Get(strParams.Get("AUDITUSERNAME"));
reportAudit.AUDITUSERNAME = strParams.Get("AUDITUSERNAME");
reportAudit.AUDITEMPNAME = empdetail.EMPNAME;
reportAudit.AUDITTYPE = (int)Enums.AuditType.审核;
reportAudit.ISFINISHED = ;
reportAudit.REPORTCODE = reportCode;
reportAudit.TASKTIME = DateTime.Now; long auditSID = m_ReportAudit_DAL.GetAuditSID(reportCode, );
if (m_ReportAudit_DAL.Exists(auditSID))
{
if (m_ReportAudit_DAL.Get(auditSID).ISFINISHED == )
{
return Content("正在提交,请稍后!");
}
else
{
reportAudit.AUDITSID = auditSID;
m_ReportAudit_DAL.Update(reportAudit);
}
}
else
{
reportAudit.AUDITSID = m_ReportAudit_DAL.GetMaxID();
m_ReportAudit_DAL.Insert(reportAudit);
} reportFlow.FLOWSERIALID = m_ReportFlow_DAL.GetMaxID();
reportFlow.OPERATOREMPNAME = AdminUtil.LoginUser.EMPNAME;
reportFlow.OPRATORUSERNAME = AdminUtil.LoginUser.USERNAME;
reportFlow.OPERATORTIME = DateTime.Now;
reportFlow.OPERATORTYPE = ;
reportFlow.OPINION = strParams.Get("OPINION"); REPORT report = m_Report_DAL.GetByReportCode(reportCode);
report.CALLBACKSTATE = ;
report.REPORTSTATEID = (long)Enums.ReportState.待审核;
report.SYSTAR = int.Parse(strParams.Get("SYSTAR"));
report.SECLEVELID = int.Parse(strParams.Get("SECLEVELID"));
report.COVERID = long.Parse(strParams.Get("COVERID"));
m_Report_DAL.Update(report); int flag = Convert.ToInt32(report.COVERID);
REPORTFILE reportFile = m_ReportFile_DAL.Get(reportCode);
if (reportFile != null)
{
string filename = Server.MapPath(m_ReportFile_DAL.Get(reportCode).FILEADDR.ToString());
if ((flag != ) && (flag != ))
{
AddPageInfo(filename, flag, reportCode);
}
} m_ReportFlow_DAL.Insert(reportFlow); return Content("OK");
}

DAL示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBHelper;
using Models; namespace DAL
{
/// <summary>
///
/// </summary>
public class ReportAudit_DAL
{
#region 变量
private OracleHelper dbHelper = new OracleHelper();
#endregion #region 添加
public void Insert(REPORTAUDIT model)
{
dbHelper.Insert(model);
}
#endregion }
}

OracleHelper数据库事务处理的更多相关文章

  1. Atitti 数据库事务处理 attilax总结

    Atitti 数据库事务处理 attilax总结 1.1. 为什么要传递Connection?1 1.2. 两种事务处理方式,一种是编程式事务处理;一种是声明...2 1.3. 事务隔离级别 2 1. ...

  2. 十三、EnterpriseFrameWork框架核心类库之数据库操作(多数据库事务处理)

    本章介绍框架中封装的数据库操作的一些功能,在实现的过程中费了不少心思,针对不同数据库的操作(SQLServer.Oracle.DB2)这方面还是比较简单的,用工厂模式就能很好解决,反而是在多数据库同时 ...

  3. SpringBoot | 1.4 数据库事务处理

    前言 前面讲解了Sring的AOP,可以知道它是用来抽取公共代码,增强方法的.而在JDBC操作数据库进行数据处理时,有很多重复的公共代码:事务的提交与回滚跟AOP的约定流程很相似.因此,Spring数 ...

  4. java中的数据库事务处理

    /*java使用事务处理,首先要求数据库支持事务,如使用MYSQL的事务功能,就要求mysql的表类型为Innodb,*/ /*InnoDB,是MySQL的数据库引擎之一 与传统的ISAM与MyISA ...

  5. MySQL数据库----事务处理

    事物处理  一. 什么是事务    一组sql语句批量执行,要么全部执行成功,要么全部执行失败 二.为什么出现这种技术 为什么要使用事务这个技术呢? 现在的很多软件都是多用户,多程序,多线程的,对同一 ...

  6. MSSQL数据库事务处理

    在日常应用中通常需要多人执行多表的操作,比如售票系统的售票功能,这时候就涉及到数据读取的一致性问题,好在MSSQL数据库也提供了事务处理功能,这里就简单的记下 语法: Begin Tran //事务处 ...

  7. Java数据库——事务处理

    在数据库中执行5条SQL语句,这些SQL语句本身需要保持一致,即要么同时成功,要么同时失败 事务基本操作 //============================================= ...

  8. Oracle数据库—— 事务处理与并发控制

    一.涉及内容 1.理解事务的概念和几个特性. 2.熟练掌握事务管理命令的使用. 3.理解并发操作的概念和数据库锁的类型. 二.具体操作 (12.5 实验) 1. 分析以下代码,说出代码中的哪些部分体现 ...

  9. JDBC学习笔记(6)——获取自动生成的主键值&处理Blob&数据库事务处理

    获取数据库自动生成的主键 [孤立的技术是没有价值的],我们这里只是为了了解具体的实现步骤:我们在插入数据的时候,经常会需要获取我们插入的这一行数据对应的主键值. 具体的代码实现: /** * 获取数据 ...

随机推荐

  1. 《C#图解教程》读书笔记之二:存储、类型和变量

    本篇已收录至<C#图解教程>读书笔记目录贴,点击访问该目录可获取更多内容. 一.类型初窥:掀起你的盖头来 (1)C程序是一组函数和数据类型,C++程序是一组函数和类,而C#程序是一组类型声 ...

  2. Wix 安装部署教程(八) 自动生成XML小工具

    这个功能类似于Heat.exe,指定文件夹,生成对应的WIX标签.Winform做的,代码简单,生成的标签需要粘贴到对应的目录才能使用,并不是一步到位. 需要设定两个参数,一个是文件夹路径,一个是文件 ...

  3. IO完成端口

    从MSDN中翻译了IO完成端口的文章,不得不说翻译的很烂,英语需要继续提高啊... 在一个多处理器系统上,IO完成端口提供一个非常高效的线程模型来处理多个异步IO请求.当一个进程创建了一个IO完成端口 ...

  4. java提高篇(五)-----抽象类与接口

    接口和内部类为我们提供了一种将接口与实现分离的更加结构化的方法. 抽象类与接口是java语言中对抽象概念进行定义的两种机制,正是由于他们的存在才赋予java强大的面向对象的能力.他们两者之间对抽象概念 ...

  5. 换个角度理解云计算之MapReduce(二)

    接上篇 3.Combiner操作 前面讲完Map操作,总结一下就是:一个大文件,分成split1~5,对应于Map1~5,每一个Map处理一个split,每一个split的每一行,会用每一个Map的m ...

  6. [译]最长回文子串(Longest Palindromic Substring) Part I

    [译]最长回文子串(Longest Palindromic Substring) Part I 英文原文链接在(http://leetcode.com/2011/11/longest-palindro ...

  7. Angularjs学习---ubuntu12.04中karma安装配置中常见的问题总结

    karma启动时出现了很多问题: 1.安装karma前提条件 安装karma首先要安装nodejs,npm然后才可以安装karma.nodejs,npm的安装过程可以参考文章:Angularjs学习- ...

  8. Atitit 理解Monad attilax总结

    Atitit 理解Monad attilax总结 但函数式编程最大的一个问题是,函数是一个数学抽象,在现实世界中不存在,1 那既然这样就够用了,还要 Monad 干嘛?Monad 的作用在这里就体现出 ...

  9. Atitti 图像处理 图像混合 图像叠加 blend 原理与实现

    Atitti 图像处理 图像混合 图像叠加 blend 原理与实现 混合模式 编辑 本词条缺少信息栏,补充相关内容使词条更完整,还能快速升级,赶紧来编辑吧! 混合模式是图像处理技术中的一个技术名词,不 ...

  10. iOS----关于第三方的运用(有待补充)

    第三方东西涵盖哪些内容? 1)第三方SDK 2)第三方框架 3)第三方功能代码的封装开源分享 4)第三方工具类等等 PS:1. 对于一个在正在深入学习的程序员而言,有时候参考学习或者使用一下第三方的东 ...