Db - DataAccess
/* Jonney Create 2013-8-12 */ /*using System.Data.OracleClient;*/
/*using System.Data.SQLite;*/
/*using MySql.Data.MySqlClient;*/
using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection; namespace Dade.DataCenter.CutBoard.Dal
{
public class SqlDataAccess : DataAccess
{
protected SqlDataAccess()
{
_databaseType = DatabaseType.SqlServer;
_connString = ConnStr;
_conn = new SqlConnection(_connString);
_cmd = _conn.CreateCommand();
_dataAdapter = new SqlDataAdapter();
_dataAdapter.SelectCommand = _cmd;
} public static string ConnStr { get; set; } public static DataAccess Instance
{
get { return new SqlDataAccess(); }
}
} public class OracleDataAccess : DataAccess
{
protected OracleDataAccess()
{
/*_databaseType = DatabaseType.Oracle;
_connString = ConnStr;
_conn = new OracleConnection(_connString);
_cmd = _conn.CreateCommand();
_dataAdapter = new OracleDataAdapter();
_dataAdapter.SelectCommand = _cmd;
_parameterChar = ":";*/
} public static string ConnStr { get; set; }
public static DataAccess Instance
{
get { return new OracleDataAccess(); }
}
} public class SqliteDataAccess : DataAccess
{
protected SqliteDataAccess()
{
/*_databaseType = DatabaseType.Sqlite;
_connString = ConnStr;
_conn = new SQLiteConnection(_connString);
_cmd = _conn.CreateCommand();
_dataAdapter = new SQLiteDataAdapter();
_dataAdapter.SelectCommand = _cmd;*/
} public static string ConnStr { get; set; }
public static DataAccess Instance
{
get { return new SqliteDataAccess(); }
}
} public class MySqlDataAccess : DataAccess
{
protected MySqlDataAccess()
{
/*_databaseType = DatabaseType.Mysql;
_connString = ConnStr;
_conn = new MySqlConnection(_connString);
_cmd = _conn.CreateCommand();
_dataAdapter = new MySqlDataAdapter();
_dataAdapter.SelectCommand = _cmd;*/
} public static string ConnStr { get; set; }
public static DataAccess Instance
{
get { return new MySqlDataAccess(); }
} } /// <summary>
/// 数据库类型
/// </summary>
public enum DatabaseType
{
SqlServer, Oracle, Mysql, Sqlite, PostgreSql, SqlCe, Access, Firebird
} /// <summary>
/// 通用数据库访问抽象类
/// </summary>
public abstract class DataAccess : IDisposable
{
protected DatabaseType _databaseType;
protected string _connString;
protected bool _useTransaction;
protected IDbConnection _conn;
protected IDbTransaction _transaction;
protected IDbCommand _cmd;
protected IDbDataAdapter _dataAdapter;
protected string _parameterChar = "@"; /// <summary>
/// 根据数据库类型返回参数
/// </summary>
/// <param name="parameterName"></param>
/// <param name="value"></param>
/// <returns></returns>
public IDbDataParameter GetParameter(string parameterName, object value)
{
try
{
IDbDataParameter parameter = null;
switch (_databaseType)
{
case DatabaseType.SqlServer:
parameter = new SqlParameter(parameterName, value ?? DBNull.Value);
break;
/*case DatabaseType.Mysql:
parameter = new MySqlParameter(parameterName, value ?? DBNull.Value);
break;*/
/*case DatabaseType.Oracle:
parameter = new OracleParameter(parameterName, value ?? DBNull.Value);
break;*/
/*case DatabaseType.Sqlite:
parameter = new SQLiteParameter(parameterName, value ?? DBNull.Value);
break;*/
default:
throw new Exception("DataAccess-->DatabaseType-->GetParameter()-->Not Implement");
}
return parameter;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 异常处理
/// </summary>
protected void DoCatch()
{
if (_useTransaction && _transaction!=null && _transaction.Connection !=null)
{
_transaction.Rollback();
_transaction.Dispose();
_transaction = null;
_useTransaction = false;
}
Close();
} /// <summary>
/// 获取是否使用事务
/// </summary>
public bool UseTransaction
{
get { return _useTransaction; }
} /// <summary>
/// 获取当前正在执行的事务
/// </summary>
public IDbTransaction Transaction
{
get { return _transaction; }
} /// <summary>
/// 获取或设置连接字符串
/// </summary>
public string ConnString
{
get { return _connString; }
set
{
_connString = value;
if (_conn != null && _conn.ConnectionString != value)
{
_conn.ConnectionString = _connString;
}
}
} /// <summary>
/// Ping服务器IP
/// </summary>
/// <param name="ip">目标主机IP</param>
/// <returns></returns>
public static bool Ping(string ip)
{
try
{
var p = new System.Net.NetworkInformation.Ping();
var options = new System.Net.NetworkInformation.PingOptions { DontFragment = true };
byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Ping..");
const int timeout = ; // Timeout 时间,单位:毫秒
System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
return reply != null && reply.Status == System.Net.NetworkInformation.IPStatus.Success;
}
catch
{
return false;
}
} /// <summary>
/// 测试连接字符串
/// </summary>
/// <returns></returns>
public bool TestConnect()
{
try
{
Open();
Close();
return true;
}
catch
{
DoCatch();
return false;
}
} /// <summary>
/// 是否存在
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public bool Exists(string sql, params IDbDataParameter[] parameters)
{
var result = GetSingle(sql, parameters);
if (result!=null && result!=DBNull.Value && result.ToString()!="")
{
return true;
}
return false;
} /// <summary>
/// 查询
/// </summary>
/// <param name="sql">查询语句</param>
/// <returns></returns>
public DataSet Query(string sql)
{
try
{
DataSet ds = new DataSet();
_cmd.Connection = _conn;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Parameters.Clear();
_dataAdapter.SelectCommand = _cmd; if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
return ds;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 查询
/// </summary>
/// <param name="type">参数类型</param>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public DataSet Query(CommandType type, string sql, params IDbDataParameter[] parameters)
{
try
{
DataSet ds = new DataSet();
_cmd.Connection = _conn;
_cmd.CommandType = type;
_cmd.CommandText = sql;
_dataAdapter.SelectCommand = _cmd;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
return ds;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 查询
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public DataSet Query(string sql, params IDbDataParameter[] parameters)
{
try
{
DataSet ds = new DataSet();
_cmd.Connection = _conn;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_dataAdapter.SelectCommand = _cmd;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
return ds;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回T类型的实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public T QuerySingle<T>(string sql, params IDbDataParameter[] parameters)
{
try
{
DataSet ds = new DataSet();
_cmd.Connection = _conn;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_dataAdapter.SelectCommand = _cmd;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
if (ds.Tables.Count> && ds.Tables[].Rows.Count>)
{
return ds.Tables[].Rows[].ToEntity<T>();
}
return default(T);
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 查询实体集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public List<T> Query<T>(string sql, params IDbDataParameter[] parameters)
{
try
{
DataSet ds = new DataSet();
_cmd.Connection = _conn;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_dataAdapter.SelectCommand = _cmd;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
if (ds.Tables.Count > && ds.Tables[].Rows.Count > )
{
return ds.Tables[].ToList<T>();
}
return null;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 查询
/// </summary>
/// <param name="cmd">IDbCommand</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public DataSet Query(IDbCommand cmd, params IDbDataParameter[] parameters)
{
try
{
DataSet ds = new DataSet();
cmd.Connection = _conn;
_dataAdapter.SelectCommand = cmd;
ReSetParameters(cmd, parameters);
if (_useTransaction)
{
_dataAdapter.Fill(ds);
}
else
{
Open();
_dataAdapter.Fill(ds);
Close();
}
return ds;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 执行sql
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteSql(string sql)
{
try
{
int result;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
_cmd.Parameters.Clear(); if (_useTransaction)
{
result = _cmd.ExecuteNonQuery();
}
else
{
Open();
result = _cmd.ExecuteNonQuery();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 执行不返回数据集的SQL/存储过程
/// </summary>
/// <param name="type">SQL类型</param>
/// <param name="sql">SQL</param>
/// <param name="parameters">参数列表</param>
/// <returns>影响行数</returns>
public int ExecuteSql(CommandType type, string sql, params IDbDataParameter[] parameters)
{
try
{
int result;
_cmd.CommandType = type;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
result = _cmd.ExecuteNonQuery();
}
else
{
Open();
result = _cmd.ExecuteNonQuery();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 执行不返回数据集的SQL
/// </summary>
/// <param name="sql">SQL</param>
/// <param name="parameters">参数列表</param>
/// <returns>影响行数</returns>
public int ExecuteSql(string sql, params IDbDataParameter[] parameters)
{
try
{
int result;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters);
if (_useTransaction)
{
result = _cmd.ExecuteNonQuery();
}
else
{
Open();
result = _cmd.ExecuteNonQuery();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 执行不返回数据集的SQL/存储过程
/// </summary>
/// <param name="cmd">IDbCommand</param>
/// <param name="parameters">参数列表</param>
/// <returns>影响行数</returns>
public int ExecuteSql(IDbCommand cmd, params IDbDataParameter[] parameters)
{
try
{
int result;
cmd.Connection = _conn;
ReSetParameters(cmd, parameters);
if (_useTransaction)
{
result = cmd.ExecuteNonQuery();
}
else
{
Open();
result = cmd.ExecuteNonQuery();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回首行首列
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object GetSingle(string sql)
{
try
{
object result;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
_cmd.Parameters.Clear(); if (_useTransaction)
result = _cmd.ExecuteScalar();
else
{
Open();
result = _cmd.ExecuteScalar();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回首行首列
/// </summary>
/// <param name="type">sql类型</param>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public object GetSingle(CommandType type, string sql, params IDbDataParameter[] parameters)
{
try
{
object result;
_cmd.CommandType = type;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters); if (_useTransaction)
result = _cmd.ExecuteScalar();
else
{
Open();
result = _cmd.ExecuteScalar();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回首行首列
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public object GetSingle(string sql, params IDbDataParameter[] parameters)
{
try
{
object result;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters); if (_useTransaction)
result = _cmd.ExecuteScalar();
else
{
Open();
result = _cmd.ExecuteScalar();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回首行首列
/// </summary>
/// <param name="cmd">IDbCommand</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public object GetSingle(IDbCommand cmd, params IDbDataParameter[] parameters)
{
try
{
object result;
cmd.Connection = _conn;
ReSetParameters(cmd, parameters); if (_useTransaction)
result = cmd.ExecuteScalar();
else
{
Open();
result = cmd.ExecuteScalar();
Close();
}
return result;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回Reader
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public IDataReader CreateReader(string sql)
{
try
{
IDataReader reader;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
_cmd.Parameters.Clear(); if (_useTransaction)
reader = _cmd.ExecuteReader();
else
{
Open();
reader = _cmd.ExecuteReader();
}
return reader;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回Reader,注意:一定要结束时手动关闭Reader、Connection
/// </summary>
/// <param name="type">sql类型</param>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public IDataReader CreateReader(CommandType type, string sql, params IDbDataParameter[] parameters)
{
try
{
IDataReader reader;
_cmd.CommandType = type;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters); if (_useTransaction)
reader = _cmd.ExecuteReader();
else
{
Open();
reader = _cmd.ExecuteReader();
}
return reader;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 返回Reader,注意:一定要结束时手动关闭Reader、Connection
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public IDataReader CreateReader(string sql, params IDbDataParameter[] parameters)
{
try
{
IDataReader reader;
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = sql;
_cmd.Connection = _conn;
ReSetParameters(_cmd, parameters); if (_useTransaction)
reader = _cmd.ExecuteReader();
else
{
Open();
reader = _cmd.ExecuteReader();
}
return reader;
}
catch
{
DoCatch();
throw;
}
} private void ReSetParameters(IDbCommand cmd, params IDbDataParameter[] parameters)
{
cmd.Parameters.Clear();
if (parameters != null && parameters.Length > )
{
for (int i = ; i < parameters.Length; i++)
{
cmd.Parameters.Add(parameters[i]);
}
}
} /// <summary>
/// 关闭Connection
/// </summary>
public void CloseReader()
{
CommitTransaction();
} /// <summary>
/// 创建和Connection(Open状态)相关联的cmd(sql预编译过)
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public IDbCommand CreateCommand(string sql)
{
try
{
Open();
IDbCommand dbCommand = _conn.CreateCommand();
dbCommand.Transaction = _transaction;
dbCommand.CommandText = sql;
dbCommand.Prepare();
return dbCommand;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 开始事务
/// </summary>
/// <returns></returns>
public bool BeginTransaction()
{
try
{
Open();
_transaction = _conn.BeginTransaction();
_cmd.Transaction = _transaction;
_useTransaction = true;
return true;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 提交事务
/// </summary>
/// <returns></returns>
public bool CommitTransaction()
{
try
{
if (_transaction != null && _transaction.Connection != null)
{
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
}
Close();
_cmd.Transaction = null;
_useTransaction = false;
return true;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 回滚事务
/// </summary>
/// <returns></returns>
public bool RollBackTransaction()
{
try
{
if (_transaction != null && _transaction.Connection != null)
{
_transaction.Rollback();
_transaction.Dispose();
_transaction = null;
}
Close();
_cmd.Transaction = null;
_useTransaction = false;
return true;
}
catch
{
DoCatch();
throw;
}
} /// <summary>
/// 打开数据库
/// </summary>
protected void Open()
{
if (_conn != null && _conn.State != ConnectionState.Open)
{
_conn.Open();
}
} /// <summary>
/// 关闭数据库
/// </summary>
protected void Close()
{
if (_conn != null && _conn.State != ConnectionState.Closed)
{
_conn.Close();
}
} /// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
if (_transaction != null && _transaction.Connection != null)
{
_transaction.Rollback();
_transaction.Dispose();
_transaction = null;
}
if (_cmd !=null)
{
_cmd.Dispose();
_cmd = null;
}
Close();
if (_conn != null)
{
_conn.Dispose();
_conn = null;
}
} /// <summary>
/// 向数据库插入实体对象
/// </summary>
/// <param name="entity">实体对象</param>
/// <param name="ignoreProperties">忽略映射的属性</param>
/// <returns></returns>
public int Insert(object entity, params string[] ignoreProperties)
{
return ExecuteSql(MakeInsertSql(entity, ignoreProperties), MakeInsertParameters(entity, ignoreProperties));
} /// <summary>
/// 更新实体
/// </summary>
/// <param name="entity"></param>
/// <param name="keys"></param>
/// <returns></returns>
public int Update(object entity, params string[] keys)
{
return ExecuteSql(MakeUpdateSql(entity, keys), MakeUpdateParameters(entity));
} /// <summary>
/// 生产Insert语句--带参数
/// </summary>
/// <param name="obj">实体对象</param>
/// <param name="ignoreProperties">忽略自曾的属性</param>
/// <returns></returns>
private string MakeInsertSql(object obj, params string[] ignoreProperties)
{
var insertHeader = string.Format("Insert Into {0} (", obj.GetType().Name);
var insertBody = ") Values(";
var pro = new List<string>();
pro.AddRange(ignoreProperties);
foreach (PropertyInfo info in obj.GetType().GetProperties())
{
if (pro.Count > && pro.Contains(info.Name))
continue;
insertHeader += info.Name + ",";
insertBody += _parameterChar + info.Name + ",";
}
insertHeader = insertHeader.Substring(, insertHeader.Length - );
insertBody = insertBody.Substring(, insertBody.Length - ) + ")";
return insertHeader + insertBody;
} /// <summary>
/// 为update产生sql脚本
/// </summary>
/// <param name="obj"></param>
/// <param name="keys"></param>
/// <returns></returns>
private string MakeUpdateSql(object obj, params string[] keys)
{
var updateHeader = string.Format("Update {0} set", obj.GetType().Name);
var updateWhere = " where 1=1";
var pro = new List<string>();
pro.AddRange(keys);
foreach (PropertyInfo info in obj.GetType().GetProperties())
{
if (pro.Count > && pro.Contains(info.Name))
{
updateWhere += " and " + info.Name + "=" + _parameterChar + info.Name;
continue;
}
if (updateHeader.EndsWith("set"))
updateHeader += " " + info.Name + "=" + _parameterChar + info.Name;
else
updateHeader += ", " + info.Name + "=" + _parameterChar + info.Name;
}
return updateHeader + updateWhere;
} /// <summary>
/// 生产Insert参数
/// </summary>
/// <param name="obj">实体对象</param>
/// <param name="ignoreProperties">忽略自曾的属性</param>
/// <returns></returns>
private IDbDataParameter[] MakeInsertParameters(object obj, params string[] ignoreProperties)
{
var parameters = new List<IDbDataParameter>();
var pro = new List<string>();
pro.AddRange(ignoreProperties);
foreach (PropertyInfo info in obj.GetType().GetProperties())
{
if (pro.Count > && pro.Contains(info.Name))
continue;
object temp = info.GetValue(obj, null);
parameters.Add(GetParameter(_parameterChar + info.Name, temp ?? DBNull.Value));
}
return parameters.ToArray();
} /// <summary>
/// 为update产生sql参数
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private IDbDataParameter[] MakeUpdateParameters(object obj)
{
var parameters = new List<IDbDataParameter>();
foreach (PropertyInfo info in obj.GetType().GetProperties())
{
object temp = info.GetValue(obj, null);
parameters.Add(GetParameter(_parameterChar + info.Name, temp ?? DBNull.Value));
}
return parameters.ToArray();
} } /// <summary>
/// DataTable和Entity的转换工具
/// </summary>
public static class DataTableUtility
{
/// <summary>
/// DataTable To IList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt)
{
if (dt == null || dt.Rows.Count == ) return null;
var list = new List<T>();
foreach (DataRow row in dt.Rows)
{
T obj = row.ToEntity<T>();
list.Add(obj);
}
return list;
} /// <summary>
/// DataRow To T
/// </summary>
public static T ToEntity<T>(this DataRow row)
{
Type objType = typeof (T);
T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo property = objType.GetProperty(column.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (property == null || !property.CanWrite)
{
continue;
}
object value = row[column.ColumnName];
if (value == DBNull.Value) value = null; property.SetValue(obj, value, null); }
return obj;
} /// <summary>
/// List To DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this List<T> list)
{
try
{
Type objType = typeof (T);
DataTable dataTable = new DataTable(objType.Name);
if (list != null ? list.Count > : false)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
foreach (PropertyDescriptor property in properties)
{
Type propertyType = property.PropertyType; //nullables must use underlying types
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
propertyType = Nullable.GetUnderlyingType(propertyType);
//enums also need special treatment
if (propertyType.IsEnum)
propertyType = Enum.GetUnderlyingType(propertyType); //probably Int32 dataTable.Columns.Add(property.Name, propertyType);
} foreach (T li in list)
{
DataRow row = dataTable.NewRow();
foreach (PropertyDescriptor property1 in properties)
{
row[property1.Name] = property1.GetValue(li) ?? DBNull.Value; //can't use null
}
dataTable.Rows.Add(row); }
}
return dataTable;
}
catch
{
return null;
}
}
} }
来,纪念一下。
Db - DataAccess的更多相关文章
- DB字段顺序与类的属性顺序一致:{Oracle.DataAccess.Client.OracleException ORA-00932: 数据类型不一致: 应为 TIMESTAMP, 但却获得 NUMBER
{Oracle.DataAccess.Client.OracleException ORA-00932: 数据类型不一致: 应为 TIMESTAMP, 但却获得 NUMBER 应用程序中类型T ...
- 反射 + 抽象工厂模式切换DB数据源(附Demo)
首先,设计模式的文章源自于程杰的<大话设计模式>这本书,这本书个人感觉很适合我,看着不累,能够安安心心的阅读学习.在这里十分感谢程杰的这本书,我博文中的例子会根据书上的例子来.为了不侵犯这 ...
- 又一个类dapper轮子:VIC.DataAccess
DataAccess Author: Victor.X.Qu Email: fs7744@hotmail.com DataAccess is a c# project for sql data map ...
- ODBC、OLE DB、 ADO、ODAC、ODP.NET
面对各式各样.越来越多的数据来源和访问需求.软件开发框架中一般都提供了统一的访问接口和方法,来屏蔽数据库底层差异. 各式各样的Provider提供者. ODBC(Open Database Conne ...
- winform连接oracle时Oracle.DataAccess.dll版本问题
1.通用TestOracle.zip部署到iis上,或直接运行程序测试当前全局程序集 protected void Button1_Click(object sender, EventArgs e) ...
- DB SQL Monitor 会话状态及等待事件监控工具
DB SQL Monitor v1.7.6 Designed by Wang Zhaoguan 工具说明 --------------------------------------- ...
- [Python设计模式] 第15章 如何兼容各种DB——抽象工厂模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 如何让一个程序,可以灵活替换数据库? 基础版本 class User(): ...
- winform连接oracle时Oracle.DataAccess.dll版本问题 Silverlight
1.通用TestOracle.zip部署到iis上,或直接运行程序测试当前全局程序集 protected void Button1_Click(object sender, EventArgs e) ...
- C#连接Oracle数据库的方法(Oracle.DataAccess.Client也叫ODP.net)
官方下载地址(ODP.net)(中文):http://www.oracle.com/technetwork/cn/topics/dotnet/downloads/index.html 官方下载地址(O ...
随机推荐
- python下使用tesserocr遇到的一些坑
我是在win7 64位系统下用的. 首先是安装tesseract,这个可以去官网下载,我使用的是3.05.1,安装时使用默认安装路径就行了,下载语言包速度很慢很慢,需要等 接下来就是安装tessero ...
- 设置和获取html、文本和值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 洛谷P5265 【模板】多项式反三角函数
题面 传送门 题解 我数学好像学得太差了 据说根据反三角函数求导公式 \[{d\over dx}\arcsin x={1\over \sqrt{1-x^2}}\] \[{d\over dx}\arct ...
- [Swift实际操作]八、实用进阶-(6)通过属性进行对象间的消息传递
本文将演示,如何通过一个对象作为另一个对象的属性,从而通过设置属性的值,来实现对象之间的消息传递.首先打开自定义视图的代码文件(CustomView.swift) import UIKit //使当前 ...
- php中签名公钥、私钥(SHA1withRSA签名)以及AES(AES/ECB/PKCS5Padding)加密解密详解
由于http请求是无状态,所以我们不知道请求方到底是谁.于是就诞生了签名,接收方和请求方协商一种签名方式进行验证,来取得互相信任,进行下一步业务逻辑交流. 其中签名用得很多的就是公钥私钥,用私钥签名, ...
- 循环神经网络RNN原理
一.循环神经网络简介 循环神经网络,英文全称:Recurrent Neural Network,或简单记为RNN.需要注意的是,递归神经网络(Recursive Neural Network)的简写也 ...
- jQuery 与 js的入口函数写法
//js的入口函数执行要比jQuery的入口函数执行得晚一些. //jq的入口函数会等待页面的加载完成才执行,但是不会等待图片的加载. //js的入口函数会等待页面加载完成,并且等待图片加载完成才开始 ...
- python在一堆目录中寻找json文件
在一个目录下,有好几层目录,里面零零散散存放着几个json文件,我要做的是用python脚本把它们都找出来,一开始就一层一层地找,用os.listdir加上for循环,根据目录树的深度确定for循环的 ...
- LESS从入门到精通
LESS从入门到精通 一.LESS是什么 LESS 是 CSS预处理语言,是 CSS 的扩展. 然后说说比较流行的几款预编译器:SASS/SCSS.LESS.Stylus. SASS 学习网站: ht ...
- python计算π及进度条显示
今天老师布置了一个课后作业,去尽可能的准确计算π的值,还要显示时间和进度条,对于python小白的我,当然是综合书上和网上的知识,自己做了一个小程序,代码如下: 一.写代码的准备工作:用pip下载第三 ...