問題
使用 泛型產生物件INSERT SQL
解決方法
internal string GetInsertString<T>(T obj) where T : class { PropertyInfo[] srcFields = obj.GetType().GetProperties( BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); List<string>columnString = new List<string(); List<string> valueString = new List<string(); foreach (var property in srcFields) { if (property.GetValue(obj, null) != null) { columnString.Add(property.Name); if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(double) || property.PropertyType == typeof(int)) { valueString.Add(property.GetValue(obj, null).ToString()); } else if (property.PropertyType == typeof(string)) { valueString.Add("'" + property.GetValue(obj, null).ToString() + "'"); } } } string sql = string.Format(@" INSERT INTO {0} ({1}) values ({2}) ", srcFields[0].DeclaringType.Name, string.Join(",", columnString.ToArray()), string.Join(",", valueString.ToArray())); return sql; }
沒有留言:
張貼留言