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


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);
}

转载于:https://www.cnblogs.com/LongHuaiYu/p/5967690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值