利用反射插入数据库与更新数据库
Posted LongHuaiYu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用反射插入数据库与更新数据库相关的知识,希望对你有一定的参考价值。
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 + "[email protected]" + name;
}
else if (!value.Equals(valueNew))
{
string Line = name + "[email protected]" + 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);
}
以上是关于利用反射插入数据库与更新数据库的主要内容,如果未能解决你的问题,请参考以下文章