#region 插入记录 public bool insertData(string sql,Object obj) { try { adapter = new SqlDataAdapter(sql, connect); sqlCBuilder = new SqlCommandBuilder(adapter); ds = new DataSet(); adapter.Fill(ds); DataRow dr = ds.Tables[0].NewRow(); Type type = obj.GetType(); PropertyInfo[] propertyArray = type.GetProperties(); foreach (PropertyInfo field in propertyArray) { Object returnValue= field.GetGetMethod().Invoke(obj, null); string fieldName = PropertiesName(field.Name); dr[fieldName] = returnValue; } ds.Tables[0].Rows.Add(dr); adapter.Update(ds); return true; } catch { return false; } finally { if (connect.State == ConnectionState.Open) { connect.Close(); } } } #endregion #region 将类的公共属性名转换为数据库对应的字段名 public string PropertiesName(string PropertyInfoName) { string str = PropertyInfoName; if (str != null) { string toLower = str.ToLowerInvariant(); string first = toLower.Substring(0,1); str = first + str.Substring(1, str.Length - 2); } return str; } #endregion
C#利用反射将数据插入数据库
最新推荐文章于 2022-04-27 08:37:43 发布