根据类生成数据库连接

 /// <summary>
        /// 根据类生成数据库连接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="tableName">如果为空  设置为类名</param>
        /// <param name="needUrlEncode"></param>
        /// <returns></returns>
        public static string GetSql<T>(T model, string tableName = "", bool needUrlEncode = false) where T : class
        {
            try
            {
                if (model == null) return "";
                if (string.IsNullOrEmpty(tableName)) tableName = typeof(T).Name.ToString();
                var sql = "INSERT INTO   " + tableName + " ({0}) VALUES  ({1});";
                var prop = model.GetType().GetProperties();
                var fields = "";
                var values = "";
                foreach (var info in prop)
                {

                    fields += string.Format("`{0}`,", info.Name);

                    if (info.PropertyType == typeof(int) || info.PropertyType == typeof(double) ||
                        info.PropertyType == typeof(float) || info.PropertyType == typeof(decimal))
                    {
                        values += string.Format("{0},", Convert.ChangeType(info.GetValue(model), info.PropertyType));
                    }
                    else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(DateTime?))
                    {
                        var v = info.GetValue(model);
                        if (v == null)
                        {
                            values += string.Format("'{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                        else
                        {

                            values += string.Format("'{0}',", (Convert.ToDateTime(v)).ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    else
                    {
                        var v = (info.GetValue(model) ?? "").ToString();
                        values += string.Format("'{0}',", needUrlEncode ? HttpUtility.UrlEncode(v) : v);
                    }

                }

                return string.Format(sql, fields.TrimEnd(','), values.TrimEnd(','));

            }
            catch (Exception ex)
            {
                LogHelper.Error("根据类生成sql 异常:" + ex.Message);
                return "";
            }




        }


转载于:https://www.cnblogs.com/change4now/p/9176690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值