最近碰上这个一个需求,需要写一个接口,将穿进来的参数,存储到数据库里,但是存到哪个库,哪个表,不确定,需要根据参数去判断,但数据结构是固定的,因为表名不是固定的,所以这就很麻烦了,不能用EF直接去add或者是addRange了。需要自己去拼sql语句。
但是本人比较懒,懒得去写sql语句,所以就写了一个自动生成Insert语句的通用方法,代码如下
/// <summary>
/// 对象拼接sql语句
/// </summary>
public class SqlBuilderHelper
{
/// <summary>
/// Insert SQL语句
/// </summary>
/// <param name="obj">要转换的对象,不可空</param>
/// <param name="tableName">要添加的表明,不可空</param>
/// <returns>
/// 空
/// sql语句
/// </returns>
public static string InsertSql<T>(T t, string tableName) where T : class
{
if (t == null || string.IsNullOrEmpty(tableName))
{
return string.Empty;
}
string columns = GetColmons(t);
if (string.IsNullOrEmpty(columns))
{
return string.Empty;
}
string values = GetValues(t);
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();
}
/// <summary>
/// BulkInsert SQL语句(批量添加)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="objs">要转换的对象集合,不可空</param>
/// <param name="tableName">>要添加的表明,不可空</param>
/// <returns>
/// 空
/// sql语句
/// </returns>
public static string BulkInsertSql<T>(List<T> objs, string tableName) where T : class
{
if (objs == null || objs.Count == 0 || string.IsNullOrEmpty(tableName))
{
return string.Empty;
}
string columns = GetColmons(objs[0]);
if (string.IsNullOrEmpty(columns))
{
return string.Empty;
}
string values = string.Join(",", objs.Select(p => string.Format("({0})", GetValues(p))).ToArray());
StringBuilder sql = new StringBuilder();
sql.Append("Insert into " + tableName);
sql.Append("(" + columns + ")");
sql.Append(" values " + values + "");
return sql.ToString();
}
/// <summary>
/// 获得类型的列名
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private static string GetColmons<T>(T obj)
{
if (obj == null)
{
return string.Empty;
}
return string.Join(",", obj.GetType().GetProperties().Select(p => p.Name).ToList());
}
/// <summary>
/// 获得值
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private static string GetValues<T>(T obj)
{
if (obj == null)
{
return string.Empty;
}
return string.Join(",", obj.GetType().GetProperties().Select(p => string.Format("'{0}'", p.GetValue(obj))).ToArray());
}
}