码迷,mamicode.com
首页 > 数据库 > 详细

利用反射插入数据库与更新数据库

时间:2016-10-16 21:38:47      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:


public int Insert<T>(T m) where T : class
{
  PropertyInfo[] pInfos = m.GetType().GetProperties();
  FieldInfo[] fInfos = m.GetType().GetFields();

  List<string> lstCol = new List<string>();
  List<OleDbParameter> lstParam = new List<OleDbParameter>();

  for (int i = 0; i < pInfos.GetLength(0); i++)
  {
    PropertyInfo pInfo = pInfos[i];
    object value = pInfo.GetValue(m, null);
    string name = pInfo.Name;
    string DeclarType = pInfo.PropertyType.Name;
    if (DeclarType.ToUpper().Contains("DateTime".ToUpper()))
    {
      value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss.fff");
    }

    lstCol.Add(name);
    lstParam.Add(new OleDbParameter("@" + name, value));
  }

  string Keys = " " + string.Join(",", lstCol.ToArray());
  string Values = " " + "@" + string.Join(",@", lstCol.ToArray());


  string sql;
  sql = @"Insert into " + GetTableName() + "("
  + Keys
  + ")values("
  + Values
  + ")";

  string ErrorMsg;
  return DBAHelp.DBA_ExecuteNonQuery(sql, (OleDbParameter[])(lstParam.ToArray()), out ErrorMsg);

}

public int Update<T>(T m, string UpdateKey) where T : class
{
  string FullName = m.GetType().FullName;
  T mNew = Activator.CreateInstance(m.GetType()) as T;

  PropertyInfo[] pInfos = m.GetType().GetProperties();
  PropertyInfo[] pInfosNew = mNew.GetType().GetProperties();


  List<string> lstCol = new List<string>();
  List<OleDbParameter> lstParam = new List<OleDbParameter>();

  OleDbParameter KeyParam = null;
  string sKey = "";

  for (int i = 0; i < pInfos.GetLength(0); i++)
  {
    PropertyInfo pInfo = pInfos[i];
    object value = pInfo.GetValue(m, null);
    string name = pInfo.Name;

    PropertyInfo pInfoNew = pInfosNew[i];
    object valueNew = pInfoNew.GetValue(mNew, null);

    if (UpdateKey.ToUpper() == name.ToUpper())
    {
      KeyParam = new OleDbParameter("@" + name, value);
      sKey = name + "=@" + name;
    }
    else if (!value.Equals(valueNew))
    {
      string Line = name + "=@" + name;
      lstCol.Add(Line);
      lstParam.Add(new OleDbParameter("@" + name, value));
    }
  }

  string Lines = string.Join(",", lstCol.ToArray());
  if (KeyParam != null)
  {
    lstParam.Add(KeyParam);
  }

  string sql;
  sql = @"Update " + GetTableName() + " Set "
  + Lines
  + " Where "
  + sKey
  + "";

  string ErrorMsg;
  return DBAHelp.DBA_ExecuteNonQuery(sql, (OleDbParameter[])(lstParam.ToArray()), out ErrorMsg);
}

利用反射插入数据库与更新数据库

标签:

原文地址:http://www.cnblogs.com/LongHuaiYu/p/5967690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!