/// <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