数据更新(二)
将List /HashTable 的数据更新到数据库某一张表中
private bool InsertIntoTable(List<DataModel> models,string conn,string tableName)
{
SqlConnection conn = new SqlConnection(conn);
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand(null, conn, tran);
Type type = typeof(DataModel);
System.Reflection.PropertyInfo[] fieldInfos = type.GetProperties();
List<SqlParameter> listSqlParameter = new List<SqlParameter>();
try
{
string fields = string.Empty;
string values = string.Empty;
foreach (var kvp in models)
{
foreach (System.Reflection.PropertyInfo fieldinfo in fieldInfos)
{
var value = fieldinfo.GetValue(kvp, null);
//在这里还可以对不需要插入的字段做限制
if (value == null || tabTable.Columns[fieldinfo.Name] ==null)
{
continue;
}
string strColumnName = "@" + fieldinfo.Name;
fields += fieldinfo.Name + ",";
values += strColumnName + ",";
//针对时间的特殊处理
SqlParameter sqlParameter = new SqlParameter(strColumnName, value);
if (fieldinfo.PropertyType==typeof(DateTime))
{
sqlParameter.DbType = DbType.DateTime;
}
listSqlParameter.Add(sqlParameter);
}
fields = fields.Substring(0, fields.Length - 1);
values = values.Substring(0, values.Length - 1);
string sql = string.Format("Insert into {0} ({1}) values ({2})", tableName, fields, values);
cmd.CommandText = sql;
cmd.Parameters.AddRange(listSqlParameter.ToArray());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
tran.Commit();
return true;
}
catch (Exception ex)
{
tran.Rollback();
return false;
}
finally
{
conn.Close();
conn.Dispose();
}
}