/// <summary>
/// 提供将MySqlDataReader转成T类型的扩展方法
/// </summary>
public static class MySqlDataReaderExt
{
private static readonly object Sync = new object(); /// <summary>
/// 属性反射信息缓存 key:类型的hashCode,value属性信息
/// </summary>
private static readonly Dictionary<int, Dictionary<string, PropertyInfo>> PropInfoCache =
new Dictionary<int, Dictionary<string, PropertyInfo>>(); /// <summary>
/// 将MySqlDataReader转成T类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="readers"></param>
/// <returns></returns>
public static T To<T>(this MySqlDataReader reader,bool IsInner=false)
where T : new()
{ if (reader == null || reader.HasRows == false) return default(T);
if (!IsInner)
{
reader.Read();
}
var res = new T();
var propInfos = GetFieldnameFromCache<T>(); for (int i = ; i < reader.FieldCount; i++)
{
var n = reader.GetName(i).ToLower();
if (propInfos.ContainsKey(n))
{
PropertyInfo prop = propInfos[n];
var isValueType = prop.PropertyType.IsValueType;
object defaultValue = null; //引用类型或可空值类型的默认值
if (isValueType)
{
if ((!prop.PropertyType.IsGenericType)||
(prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() != typeof(Nullable<>)))
{
defaultValue = ; //非空值类型的默认值
}
}
var type= reader.GetFieldType(i);
var v = reader.GetValue(i);
dynamic temp=null;
if (prop.PropertyType.Name == "Int32" && v != DBNull.Value)
{
temp = Convert.ToInt32(v);
}
else if (prop.PropertyType.Name == "Boolean" && v != DBNull.Value)
{
if ((type == typeof(int) || type == typeof(long)))
{
temp = Convert.ToInt32(v) == ;
}
} temp = temp ?? v;
prop.SetValue(res, (Convert.IsDBNull(temp) ? defaultValue : temp));
}
} return res;
} private static Dictionary<string, PropertyInfo> GetFieldnameFromCache<T>()
{
var hashCode = typeof (T).GetHashCode();
var filedNames = GetFieldName<T>();
Dictionary<string, PropertyInfo> res;
lock (Sync)
{
if (!PropInfoCache.ContainsKey(hashCode))
{
PropInfoCache.Add(hashCode, filedNames);
}
res = PropInfoCache[hashCode];
}
return res;
} /// <summary>
/// 获取一个类型的对应数据表的字段信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private static Dictionary<string, PropertyInfo> GetFieldName<T>()
{
var props = typeof (T).GetProperties();
return props.ToDictionary(item => item.GetFieldName());
} /// <summary>
/// 将MySqlDataReader转成List类型
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="reader">数据读取器</param>
/// <returns></returns>
public static List<T> ToList<T>(this MySqlDataReader reader)
where T : new()
{
if (reader == null || reader.HasRows == false) return null;
var res = new List<T>();
while (reader.Read())
{
res.Add(reader.To<T>(true));
}
return res;
} /// <summary>
/// 获取该属性对应到数据表中的字段名称
/// </summary>
/// <param name="propInfo"></param>
/// <returns></returns>
public static string GetFieldName(this PropertyInfo propInfo)
{
var fieldname = propInfo.Name;
var attr = propInfo.GetCustomAttributes(false);
foreach (var a in attr)
{
if (a is DataFieldAttribute)
{
fieldname = (a as DataFieldAttribute).Name;
break;
}
}
return fieldname.ToLower();
}
public static string ToUpdateSql(this object model, string key, ref List<KeyValuePair<string, object>> list)
{
try
{ StringBuilder sql = new StringBuilder();
string fileds = "";
Type m = model.GetType();
PropertyInfo[] property = m.GetProperties();
sql.Append("update " + m.Name + " set ");
for (int i = ; i < property.Length; i++)
{
if (property[i].Name == key)
continue;
if (property[i].GetValue(model, null) != null)
{
fileds += property[i].Name + "=@s" + i + " ,"; list.Add(new KeyValuePair<string, object>("@s" + i, property[i].GetValue(model, null)));
} }
fileds = fileds.Substring(, fileds.LastIndexOf(",", StringComparison.Ordinal));
sql.Append(fileds);
sql.Append(" where " + key + "=@key");
list.Add(new KeyValuePair<string, object>("@key", m.GetProperty(key).GetValue(model, null).ToString()));
return sql.ToString();
}
catch
{
return "";
} } public static string ToAddSql(this object model, string key, ref List<KeyValuePair<string, object>> list)
{
try
{ StringBuilder sql = new StringBuilder();
Type m = model.GetType();
PropertyInfo[] property = m.GetProperties(); string values = string.Empty;
string keys = string.Empty;
for (int i = ; i < property.Length; i++)
{
if (property[i].Name == key || property[i].GetValue(model, null) == null)
continue;
keys += property[i].Name + " ,";
values += "@s" + i + ","; list.Add(new KeyValuePair<string, object>("@s" + i, property[i].GetValue(model, null)));
}
keys = keys.Substring(, keys.LastIndexOf(','));
values = values.Substring(, values.LastIndexOf(','));
sql.AppendFormat("insert into " + m.Name + "({0}) values({1});select @@IDENTITY", keys, values);
//list.Add(new KeyValuePair<string, object>("@key", M.GetProperty(key).GetValue(model, null).ToString()));
return sql.ToString();
}
catch
{
return "";
} } public static string ToAddSql(this object model, string key)
{
try
{ StringBuilder sql = new StringBuilder();
Type m = model.GetType();
PropertyInfo[] property = m.GetProperties(); string values = string.Empty;
string keys = string.Empty;
for (int i = ; i < property.Length; i++)
{
if (property[i].Name == key)
continue;
if (property[i].GetValue(model, null) != null)
{ keys += property[i].Name + " ,";
if (property[i].PropertyType.Name.Contains("String") ||
property[i].PropertyType.FullName.Contains("DateTime"))
{
values += "'" + property[i].GetValue(model, null) + "',";
}
else
{
values += property[i].GetValue(model, null) + ",";
}
}
}
keys = keys.Substring(, keys.LastIndexOf(','));
values = values.Substring(, values.LastIndexOf(','));
sql.AppendFormat("insert into " + m.Name + "({0}) values({1});select @@IDENTITY;", keys, values);
return sql.ToString();
}
catch
{
return "";
}
}
} public class DataFieldAttribute : Attribute
{
public string Name { get; set; } public DataFieldAttribute()
{ } public DataFieldAttribute(string name)
{
Name = name;
}
}
 /// <summary>
/// inset
/// </summary>
/// <param name="ID">主键id</param>
/// <returns>int返回ID</returns>
public static string Insert(object Model, string ID)
{
List<MySqlParameter> param = new List<MySqlParameter>();
StringBuilder commandText = new StringBuilder(" insert into ");
Type type = Model.GetType();
//T mode = Activator.CreateInstance<T>();
string tableName = type.Name;
PropertyInfo[] pros = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
StringBuilder filedStr = new StringBuilder();
StringBuilder paramStr = new StringBuilder();
int len = pros.Length;
//if (!string.IsNullOrEmpty(ID))
//{ param = new MySqlParameter[len - 1]; }
//else
//{
// param = new MySqlParameter[len - 1];
//}
//int paramLindex = 0;
for (int i = ; i < len; i++)
{
string fieldName = pros[i].Name;
if (!fieldName.ToUpper().Equals(ID.ToUpper()) && pros[i].GetValue(Model, null) != null)
{
filedStr.Append(fieldName);
string paramName = "@" + fieldName;
paramStr.Append(paramName);
filedStr.Append(",");
paramStr.Append(",");
object val = type.GetProperty(fieldName).GetValue(Model, null);
if (val == null)
{
val = DBNull.Value;
}
param.Add(new MySqlParameter(fieldName, val));
//paramLindex++;
}
} commandText.Append(tableName);
commandText.Append("(");
commandText.Append(filedStr.ToString().Substring(, filedStr.ToString().LastIndexOf(',')));
commandText.Append(") values (");
commandText.Append(paramStr.ToString().Substring(, paramStr.ToString().LastIndexOf(',')));
commandText.Append(");select @@IDENTITY");
string InsertID = DbHelperSQL.ExecuteScalar(commandText.ToString(), param.ToArray());
return InsertID; }
///// <summary>
///// inset
///// </summary>
///// <param name="ID">主键id</param>
///// <returns>int返回ID</returns>
//public static string InsertTemp(object Model, string ID)
//{
// List<MySqlParameter> param = new List<MySqlParameter>();
// StringBuilder commandText = new StringBuilder(" insert into ");
// Type type = Model.GetType();
// //T mode = Activator.CreateInstance<T>();
// string tableName = type.Name;
// PropertyInfo[] pros = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
// StringBuilder filedStr = new StringBuilder();
// StringBuilder paramStr = new StringBuilder();
// int len = pros.Length;
// //if (!string.IsNullOrEmpty(ID))
// //{ param = new MySqlParameter[len - 1]; }
// //else
// //{
// // param = new MySqlParameter[len - 1];
// //}
// //int paramLindex = 0;
// for (int i = 0; i < len; i++)
// {
// string fieldName = pros[i].Name;
// if (!fieldName.ToUpper().Equals(ID.ToUpper()) && pros[i].GetValue(Model, null) != null)
// {
// filedStr.Append(fieldName);
// string paramName = "@" + fieldName;
// paramStr.Append(paramName);
// filedStr.Append(",");
// paramStr.Append(",");
// object val = type.GetProperty(fieldName).GetValue(Model, null);
// if (val == null)
// {
// val = DBNull.Value;
// }
// param.Add(new MySqlParameter(fieldName, val));
// //paramLindex++;
// }
// } // commandText.Append(tableName);
// commandText.Append("(");
// commandText.Append(filedStr.ToString().Substring(0, filedStr.ToString().LastIndexOf(',')));
// commandText.Append(") values (");
// commandText.Append(paramStr.ToString().Substring(0, paramStr.ToString().LastIndexOf(',')));
// commandText.Append(");select @@IDENTITY");
// string InsertID = DbHelperSQL.ExecuteScalarTem(commandText.ToString(), param.ToArray());
// return InsertID; //} /// <summary>
/// update
/// </summary>
/// <param name="ID">主键id</param>
/// <returns>int返回影响条数</returns>
public static int Update(object Model, string ID)
{
List<MySqlParameter> param = new List<MySqlParameter>();
Type type = Model.GetType();
string tableName =type.Name;
//T model = Activator.CreateInstance<T>();
StringBuilder commandText = new StringBuilder(" update " + tableName + " set ");
PropertyInfo[] pros = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
StringBuilder filedStr = new StringBuilder();
//int HaveNUM = 0;
int len = pros.Length;
//for (int i = 0; i < len; i++)
//{
// if (type.GetProperty(pros[i].Name).GetValue(Model, null) != null)
// {
// HaveNUM++;
// }
//}
if (type.GetProperty(ID).GetValue(Model, null) == null)
{
return ;
}
else if (type.GetProperty(ID).GetValue(Model, null).ToString() == "")
{
return ;
}
for (int i = ; i < len; i++)
{ string fieldName = pros[i].Name;
if (!fieldName.ToUpper().Equals(ID.ToUpper()))
{
if (type.GetProperty(fieldName).GetValue(Model, null) != null)
{
filedStr.Append(fieldName + "=@" + fieldName);
filedStr.Append(",");
object val = type.GetProperty(fieldName).GetValue(Model, null);
if (val == null)
{ val = DBNull.Value;
} param.Add(new MySqlParameter(fieldName, val)); }
}
} param.Add(new MySqlParameter(ID, type.GetProperty(ID).GetValue(Model, null)));
commandText.Append(filedStr.ToString().Substring(, filedStr.ToString().LastIndexOf(',')));
commandText.Append(" where " + ID + "=@" + ID);
object obj2 = DbHelperSQL.ExecuteSql(commandText.ToString(), param.ToArray());
if (obj2 == null)
{
return ;
}
else
{
return Convert.ToInt32(obj2);
} }
/// <summary>
/// updateList 事务修改
/// </summary>
/// <param name="ID">主键id</param>
/// <returns>int</returns>
public static int Update<T>(List<T> List, string ID)
{
List<CommandInfo> ListComd = new List<CommandInfo>();
List<KeyValuePair<string, object>> listparam;
//CommandInfo Model = new CommandInfo();
List<MySqlParameter> sqlParam;
MySqlParameter param;
string sql = "";
foreach (var item in List)
{
listparam = new List<KeyValuePair<string, object>>();
sqlParam = new List<MySqlParameter>();
sql = item.ToUpdateSql(ID, ref listparam);
foreach (var Keyvalue in listparam)
{
param = new MySqlParameter(Keyvalue.Key, Keyvalue.Value.GetType());
param.Value = Keyvalue.Value;
sqlParam.Add(param);
}
ListComd.Add(new CommandInfo(sql, sqlParam.ToArray(), EffentNextType.ExcuteEffectRows));
}
return DbHelperSQL.ExecuteSqlTran(ListComd);
}
/// <summary>
/// updateList 事务增加
/// </summary>
/// <param name="ID">主键id</param>
/// <returns>int</returns>
public static int Insert<T>(List<T> List, string ID)
{
List<CommandInfo> ListComd = new List<CommandInfo>();
List<KeyValuePair<string, object>> listparam;
//CommandInfo Model = new CommandInfo();
List<MySqlParameter> sqlParam;
MySqlParameter param;
string sql = "";
foreach (var item in List)
{
listparam = new List<KeyValuePair<string, object>>();
sqlParam = new List<MySqlParameter>();
sql = item.ToAddSql(ID, ref listparam);
foreach (var Keyvalue in listparam)
{
//param = new MySqlParameter(Keyvalue.Key, GetDbType(Keyvalue.Value.GetType()));
param = new MySqlParameter(Keyvalue.Key, Keyvalue.Value);
//param.Value = Keyvalue.Value;
sqlParam.Add(param);
}
ListComd.Add(new CommandInfo(sql, sqlParam.ToArray(), EffentNextType.ExcuteEffectRows));
}
return DbHelperSQL.ExecuteSqlTran(ListComd);
}
/// <summary>
/// 获取类型
/// </summary>
/// <returns></returns>
private static MySqlDbType GetDbType(Type t)
{
if (t==typeof(string))
{
return MySqlDbType.String;
}
if (t==typeof(int))
{
return MySqlDbType.Int32;
}
if (t==typeof(bool))
{
return MySqlDbType.Int16;
}
if (t==typeof(DateTime))
{
return MySqlDbType.DateTime;
}
return MySqlDbType.String;
}

C# 数据库数据动态插入(反射)的更多相关文章

  1. Java实现PDF和Excel生成和数据动态插入以及导出

    一.序言 Excel.PDF的导出.导入是我们工作中经常遇到的一个问题,刚好今天公司业务遇到了这个问题,顺便记个笔记以防下次遇到相同的问题而束手无策. 公司有这么两个需求: 需求一.给了一个表单,让把 ...

  2. Prometheus时序数据库-数据的插入

    Prometheus时序数据库-数据的插入 前言 在之前的文章里,笔者详细的阐述了Prometheus时序数据库在内存和磁盘中的存储结构.有了前面的铺垫,笔者就可以在本篇文章阐述下数据的插入过程. 监 ...

  3. postgresql 存储过程动态插入数据 2

    最近学习postgresql,正一个小活要用上,所以就开始学习了!然而,学习的过程极其艰辛,但却也充满了乐趣. 一般来说数据库的操作不外如何增,删,改,查,而首要的就是要添加数据到数据库中,因为以前的 ...

  4. ThinkPHP增加数据库字段后插入数据为空的解决办法

    今天用ThinkPHP做了一个简单的商品发布系统,数据库本来只有四个字段id,name,url,image.id是主键,name是商品名称,url是商品链接,image是商品图片,做的差不多了,发现还 ...

  5. 如何用asp.net MVC框架、highChart库从sql server数据库获取数据动态生成柱状图

    如何用asp.net MVC框架.highChart库从sql server数据库获取数据动态生成柱状图?效果大概是这样的,如图: 请问大侠这个这么实现呢?

  6. C# 批量插入表SQLSERVER SqlBulkCopy往数据库中批量插入数据

    #region 帮助实例:SQL 批量插入数据 多种方法 /// <summary> /// SqlBulkCopy往数据库中批量插入数据 /// </summary> /// ...

  7. C#中几种数据库的大数据批量插入

    C#语言中对SqlServer.Oracle.SQLite和MySql中的数据批量插入是支持的,不过Oracle需要使用Orace.DataAccess驱动. IProvider里有一个用于实现批量插 ...

  8. C#:几种数据库的大数据批量插入

    在之前只知道SqlServer支持数据批量插入,殊不知道Oracle.SQLite和MySql也是支持的,不过Oracle需要使用Orace.DataAccess驱动,今天就贴出几种数据库的批量插入解 ...

  9. EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的

    我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...

随机推荐

  1. 二分图最大权匹配模板(pascal)

    用uoj80的题面了: 从前一个和谐的班级,有 nlnl 个是男生,有 nrnr 个是女生.编号分别为 1,…,nl1,…,nl 和 1,…,nr1,…,nr. 有若干个这样的条件:第 vv 个男生和 ...

  2. 去除百度搜索结果中的广告的 js 代码

    在百度页面下控制台里执行如下代码, 然后关掉控制台 setInterval(() => { try{ Array.from( document.querySelectorAll('#conten ...

  3. spring MVC 统一异常处理(webapi和web分开处理)

    转载: http://blog.csdn.net/m13321169565/article/details/7641978 http://blog.csdn.net/ethan_fu/article/ ...

  4. MVC 锚点

    MVC 锚点 linkText:生成的链接所显示的文字 actionName:对应控制器的方法 routeValues:向对应的action传递的参数 controlName:指定控制器的名称 htm ...

  5. hdu 1540 Tunnel Warfare (线段树 区间合并)

    Tunnel Warfare Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  6. c# 移除文本文件里的某一行

    参考自:http://zhidao.baidu.com/question/87467507.html //定义一个变量用来存读到的东西 string text = ""; //用一 ...

  7. 【BZOJ1967】[AHOI2005]穿越磁场(最短路)

    [BZOJ1967][AHOI2005]穿越磁场(最短路) 题面 BZOJ 洛谷 题解 一个显然的思路是这样的,我们的正方形的边长把整个平面割成了若干块,显然每个联通块都可以看着做一个点,那么接下来只 ...

  8. 【转】如何在您的PCB大作上添加二维码?

    开篇先给大家来段新闻截选: “8月20日,新加坡总理李显龙在国庆群众大会上演讲时,称中国移动支付(电子支付)领先全球,新加坡的移动支付还很落后,上海路边摊都有移动支付,新加坡人去上海就像乡巴佬. 这番 ...

  9. 【转】巧用CAT706做掉电检测

    相信大家都会遇到这样的情况,当你正在敲一份文档或一段代码时,啪的一下停电啦,我擦……,我的代码……,我的图纸……,我刚写好的文章…….但是在嵌入式系统中也会遇到类似的情况,通常会导致嵌入式系统数据,程 ...

  10. JavaScript学习复习

    JavaScript 输出 使用 window.alert() 弹出警告框. 使用 document.write() 方法将内容写到 HTML 文档中. 使用 innerHTML 写入到 HTML 元 ...