实体类取SQL

单表插入SQL

/// <summary>
        /// 根据实体数据获取插入SQL
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="tableName">表名称</param>
        /// <param name="model">实体</param>
        /// <returns></returns>
        public static string GetInsertSqlByModel<T>(string tableName, T model)
        {
            StringBuilder sbInsert = new StringBuilder($"Insert into {tableName}( ");
            StringBuilder sbValues = new StringBuilder($" Values ( ");
            System.Reflection.PropertyInfo[] properties = model.GetType().GetProperties();
            foreach (System.Reflection.PropertyInfo property in properties)
            {
                string value = property.GetValue(model, null).ToString().Trim();
                string name = property.Name;
                if (value != null && value.Length > 0)
                {
                    sbInsert.Append(name + ",");
                    sbValues.Append($"'{value}',");
                }
            }
            sbInsert.Remove(sbInsert.Length - 1, 1);
            sbValues.Remove(sbValues.Length - 1, 1);
            sbInsert.Append(")");
            sbValues.Append(" )");
            string insertSql = sbInsert.ToString() + sbValues.ToString();

            return insertSql.ToString();
        }

 

上一篇:Codeforces Round #722 (Div. 2) 题解


下一篇:基本数据类型int,包装类Integer,字符串String的相互转化--》NumberFormatException异常