使用反射实现生成添加、修改sql语句

1.生成添加sql语句 

//单独一个model时
public static string InsertSql(T t)
        {
            Type type = typeof(T);
            string tableName = type.Name;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb_v = new StringBuilder();
            sb.Append("insert into ");
            sb.Append(tableName);
            sb.Append("(");

            sb_v.Append(" values (");
            foreach (var pi in type.GetProperties())
            {
                if (pi != null)
                {
                    object[] pk = pi.GetCustomAttributes(false);
                    if (pk.Count() > 0)
                    {
                        Col_Attribute ca = pk[0] as Col_Attribute;
                        if (ca.IsPrimaryKey && ca.IsIdentity)//主键,且自增 主键不参与插入
                            continue;
                        if (ca.NotTableField) //不是表字段 不插入
                            continue;
                    }


                    object value = pi.GetValue(t, null);
                    if (value == null)
                        continue; //未给值,null

                    sb.Append("[" + pi.Name + "],");
                    value = CommonFunc.UnInjection(value);
                    if (value == null)
                        sb_v.Append("null" + ",");
                    else if (value.GetType() == typeof(int) || value.GetType() == typeof(decimal) || value.GetType() == typeof(double) || value.GetType() == typeof(long) || value.GetType() == typeof(float))
                        sb_v.Append(value + ",");
                    else
                        sb_v.Append("'" + value + "',");
                }
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(")");

            sb_v.Remove(sb_v.Length - 1, 1);
            sb_v.Append(")");

            sb.Append(sb_v);


            return sb.ToString();
        }

//多个model时
public static string InsertSql(List t)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("begin ");
            foreach (T item in t)
            {
                sb.Append(InsertSql(item));
                sb.Append(";");
            }
            sb.Append("end;");
            return sb.ToString();
        }

 2.生成修改sql语句

//更新一个实体
public static string UpdateSql(T t)
        {
            string PrimaryName = "";//主键名、值
            object ParmaryValue = null;

            Type type = typeof(T);
            string tableName = type.Name;


            StringBuilder sb = new StringBuilder();
            StringBuilder sb_u = new StringBuilder();
            sb.Append("update ");
            sb.Append(tableName);
            sb.Append(" set ");

            foreach (var pi in type.GetProperties())
            {
                if (pi != null)
                {
                    object value = pi.GetValue(t, null);//字段对应的值
                    #region 主键
                    object[] obj = pi.GetCustomAttributes(false);//取特性
                    if (obj.Count() > 0)
                    {
                        Col_Attribute ca = obj[0] as Col_Attribute;
                        if (ca.IsPrimaryKey)//主键
                        {
                            PrimaryName = pi.Name;
                            ParmaryValue = value;
                            continue;
                        }
                        if (ca.NotTableField) //不是表字段
                            continue;
                    }
                    #endregion
                    if (value == null) continue; //如果该字段为null不更新
                    value = CommonFunc.UnInjection(value);
                    sb_u.Append("[" + pi.Name + "]=");

                    if (value == null)
                        sb_u.Append("null" + ",");
                    else if (value.GetType() == typeof(int) || value.GetType() == typeof(decimal) || value.GetType() == typeof(double) || value.GetType() == typeof(long) || value.GetType() == typeof(float))
                        sb_u.Append(value + ",");
                    else
                        sb_u.Append("'" + value + "',");
                }
            }

            if (string.IsNullOrEmpty(PrimaryName))
                throw new Exception("需要主键(请检查表是否设置主键以及MODEL主键字段是否设置特性)");
            else if (ParmaryValue == null)
                throw new Exception("请检查主键值");
            else if (string.IsNullOrEmpty(sb_u.ToString()))
                throw new Exception("无更新");
            else
            {
                sb_u.Remove(sb_u.Length - 1, 1);
                sb.Append(sb_u);
                sb.Append(" where ");
                sb.Append("[" + PrimaryName + "] = " + ParmaryValue);
            }

            return sb.ToString();
        }

//更新多个实体
public static string UpdateSql(List t)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("begin ");
            foreach (T item in t)
            {
                sb.Append(UpdateSql(item));
                sb.Append(";");
            }
            sb.Append("end;");
            return sb.ToString();
        }

上面两种需要用CMDB插件

下面给出不需要用插件的

3,插入

 /// 
        /// Insert SQL语句
        /// 
        /// 要转换的对象,不可空
        /// 要添加的表明,不可空
        /// 
        /// 空
        /// sql语句
        /// 
        public static string InsertSql(T t, string tableName) where T : class
        {
            if (t == null || string.IsNullOrEmpty(tableName))
            {
                return string.Empty;
            }
            string columns = string.Join(",", t.GetType().GetProperties().Select(p => p.Name).ToList());
            if (string.IsNullOrEmpty(columns))
            {
                return string.Empty;
            }
            string values = string.Join(",", t.GetType().GetProperties().Select(p => string.Format("'{0}'", p.GetValue(t, null))).ToArray());
            if (string.IsNullOrEmpty(values))
            {
                return string.Empty;
            }
            StringBuilder sql = new StringBuilder();
            sql.Append("Insert into " + tableName);
            sql.Append("(" + columns + ")");
            sql.Append(" values(" + values + ")");
            return sql.ToString();
        }

        /// 
        /// Insert SQL语句(批量添加)
        /// 
        /// 类型
        /// 要转换的对象集合,不可空
        /// >要添加的表明,不可空
        /// 
        /// 空
        /// sql语句
        /// 
        public static string InsertSql(List objs, string tableName) where T : class
        {
            if (objs == null || objs.Count == 0 || string.IsNullOrEmpty(tableName))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("begin ");
            foreach (var item in objs)
            {
                sb.Append(InsertSql(item, tableName));
                sb.Append(";");
            }
            sb.Append("end;");
            return sb.ToString();
        }

4,更新

 /// 
        /// Update SQL语句
        /// 
        /// 要转换的对象,不可空
        /// 要添加的表明,不可空
        /// 
        /// 空
        /// sql语句
        /// 
        public static string UpdateSql(T t, string tableName) where T : class
        {
            if (t == null || string.IsNullOrEmpty(tableName))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("update ");
            sb.Append(tableName);
            sb.Append(" set ");
            PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < myPropertyInfo.Length; i++)
            {
                PropertyInfo pi = myPropertyInfo[i];
                if (pi.Name.ToUpper() == "NUMBER" || pi.Name.ToUpper() == "TYPE")
                    sb.Append("\"" + pi.Name.ToUpper() + "\"");
                else
                    sb.Append(pi.Name);
                if (pi.PropertyType != typeof(DateTime))
                {
                    sb.Append("='" + pi.GetValue(t, null) + "'");
                }
                else
                    sb.Append("=to_date('"+ pi.GetValue(t, null)+"','" + "yyyy-MM-dd HH24:MI:ss" + "')");
                if (i != myPropertyInfo.Length - 1)
                    sb.Append(",");
            }
            sb.Append(" where ariid = " + myPropertyInfo[0].GetValue(t, null));

            return sb.ToString();
        }


        /// 
        /// Update SQL语句(批量修改)
        /// 
        /// 类型
        /// 要转换的对象集合,不可空
        /// >要添加的表明,不可空
        /// 
        /// 空
        /// sql语句
        /// 
        public static string UpdateSql(List objs, string tableName) where T : class
        {
            if (objs == null || objs.Count == 0 || string.IsNullOrEmpty(tableName))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("begin ");
            foreach (var item in objs)
            {
                sb.Append(UpdateSql(item, tableName));
                sb.Append(";");
            }
            sb.Append("commit; end;");
            return sb.ToString();
        }

 

你可能感兴趣的:(C#,反射,sql,添加更新)