Java教程

实体类取SQL

本文主要是介绍实体类取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();
        }

 

这篇关于实体类取SQL的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!