oracle动态添加一条记录

2017-05-04 20:37

/// <summary>
/// 添加一个实体
/// </summary>
/// <typeparam name="T">实体名称</typeparam>
/// <param name="dic">需要添加的字段</param>
/// <returns>返回影响的行数</returns>
public static int AddEntity<T>(Dictionary<string, object> dic) where T : class,new()
{

T t = new T();
var propertys = typeof(T).GetProperties();
string FieldKey = string.Empty;
string FieldValue = string.Empty;
foreach (var p in propertys)
{
foreach (var key in dic.Keys)
{
if (p.Name.ToUpper() == key.ToUpper())
{
FieldKey += p.Name.ToUpper() + ",";
if (p.PropertyType == typeof(int))
{
try
{
if (string.IsNullOrEmpty(dic[key].ToString()))
{
FieldValue += Convert.ToInt32(dic[key]) + ",";
}
else
{
FieldValue += Convert.ToInt32(dic[key]) + ",";
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("提示:" + ex.Message);
}
}
else if (p.PropertyType == typeof(DateTime))
{
// 如果时间为空,就将当前时间赋值
if (string.IsNullOrEmpty(dic[key].ToString()))
{
FieldValue += "to_date('" + Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "','yyyy-mm-dd HH24:mi:ss'),";
}
else
{
FieldValue += "to_date('" + Convert.ToDateTime(dic[key].ToString()) + "','yyyy-mm-dd HH24:mi:ss'),";
}
}
else
{
FieldValue += "'" + dic[key].ToString() + "',";
}
}
}
}
string tableName = GetTableNameToModel(t);
string sql = "insert into " + tableName + "(" + FieldKey.TrimEnd(',').ToString() + ") values(" + FieldValue.TrimEnd(',').ToString() + ")";
int result = OracleHelper.ExecuteNonQuery(sql);
return result;
}