转:http://www.cnblogs.com/the7stroke/archive/2012/04/22/2465597.html

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

using System.Data;

public class SQLHelper

{

/// <summary>

/// 插入单个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="entity"></param>

/// <returns></returns>

public static int Insert<T>(T entity)

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "INSERT INTO [" + type.Name + "] (";

string colsName = string.Empty;

string colsValues = string.Empty;

foreach (PropertyInfo item in type.GetProperties())

{

if (item.Name.ToLower() == "id")          //不插入自动增长列

continue;

if (item.GetValue(entity, null) == null)    //null值也不插入

continue;

colsName += "[" + item.Name + "],";

if (item.PropertyType.ToString().Contains("String") || item.PropertyType.ToString().Contains("Date"))

colsValues += "'" + item.GetValue(entity, null) + "',";

else

colsValues += item.GetValue(entity, null) + ",";

}

colsName = colsName.Substring(0, colsName.LastIndexOf(','));        //不要最后一个 ,

colsValues = colsValues.Substring(0, colsValues.LastIndexOf(','));  //不要最后一个 ,

sql += colsName + ") VALUES ( " + colsValues + ")";

#endregion

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 插入多个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="ListEntity"></param>

public static void Insert<T>(List<T> ListEntity)

{

#region 生成 SQL 语句

List<string> sqlList = new List<string>();

foreach (var entity in ListEntity)

{

Type type = entity.GetType();

string sql = "INSERT INTO [" + type.Name + "] (";

string colsName = string.Empty;

string colsValues = string.Empty;

foreach (PropertyInfo item in type.GetProperties())

{

if (item.Name.ToLower() == "id")          //不插入自动增长列

continue;

if (item.GetValue(entity, null) == null)    //null值也不插入

continue;

colsName += "[" + item.Name + "],";

if (item.PropertyType.ToString().Contains("String") || item.PropertyType.ToString().Contains("Date"))

colsValues += "'" + item.GetValue(entity, null) + "',";

else

colsValues += item.GetValue(entity, null) + ",";

}

colsName = colsName.Substring(0, colsName.LastIndexOf(','));        //不要最后一个 ,

colsValues = colsValues.Substring(0, colsValues.LastIndexOf(','));  //不要最后一个 ,

sql += colsName + ") VALUES ( " + colsValues + ");";

sqlList.Add(sql);

}

#endregion

DBHelperSQL.ExcuteTransactionSql(sqlList);

}

/// <summary>

/// 删除单个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="Id"></param>

/// <returns></returns>

public static int Delete<T>(int Id)

{

Type type = typeof(T);

string sql = "DELETE [" + type.Name + "] WHERE Id IN ( " + Id + ")";

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 删除单个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="Id"></param>

/// <returns></returns>

public static int Delete<T>(T entity)

{

Type type = typeof(T);

string sql = "DELETE [" + type.Name + "] WHERE Id IN ( ";

foreach (PropertyInfo item in type.GetProperties())

{

if (item.Name.ToLower() == "id")          //不插入自动增长列

{

sql += item.GetValue(entity,null) + ")";

break;

}

}

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 删除多个实体

/// </summary>

/// <typeparam name="T">实体类型</typeparam>

/// <param name="Ids">Id 数组</param>

/// <returns></returns>

public static int Delete<T>(int[] Ids)

{

Type type = typeof(T);

string sql = "DELETE [" + type.Name + "] WHERE Id IN ( ";

foreach (var item in Ids)

{

sql +=  Ids + ",";

}

sql = sql.Substring(0, sql.LastIndexOf(','));   //不要最后一个 ,

sql += " )";

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 删除多个实体

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="listEntity">实体数组</param>

/// <returns></returns>

public static int Delete<T>(List<T> listEntity)

{

if (listEntity == null || listEntity.Count == 0)

{

return 0;

}

Type type = typeof(T);

string sql = "DELETE [" + type.Name + "] WHERE Id IN ( ";

foreach (var entity in listEntity)

{

foreach (PropertyInfo property in entity.GetType().GetProperties())

{

if (property.Name.ToLower() == "id")          //不插入自动增长列

{

sql += property.GetValue(entity, null) + ",";

break;

}

}

}

sql = sql.Substring(0, sql.LastIndexOf(','));  //不要最后一个 ,

sql += " )";

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 修改单个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="entity"></param>

/// <returns></returns>

public static int Update<T>(T entity)

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "UPDATE [" + type.Name + "] SET ";

object ID = 0;

foreach (PropertyInfo item in type.GetProperties())

{

if (item.Name.ToLower() == "id")          //不插入自动增长列

{

ID = item.GetValue(entity, null);

continue;

}

if (item.GetValue(entity, null) == null)    //null值也不插入

continue;

sql += "[" + item.Name + "]=";

if (item.PropertyType.ToString().Contains("String") || item.PropertyType.ToString().Contains("Date"))

sql += "'" + item.GetValue(entity, null) + "',";

else

sql += item.GetValue(entity, null) + ",";

}

sql = sql.Substring(0, sql.LastIndexOf(','));        //不要最后一个,

sql += " WHERE ID=" + ID;

#endregion

return DBHelperSQL.ExecuteNonQuery(sql);

}

/// <summary>

/// 根据ID获取单个实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="ID"></param>

/// <returns></returns>

public static T Get<T>(int ID)

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "SELECT * FROM [" + type.Name + "] WHERE ID=" + ID;

#endregion

return DBHelperSQL.ExecuteDataTable(sql).ToSingleEntity<T>();

}

/// <summary>

/// 获取所有实例

/// </summary>

/// <typeparam name="T"></typeparam>

/// <returns></returns>

public static List<T> Get<T>()

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "SELECT * FROM [" + type.Name + "]";

#endregion

return DBHelperSQL.ExecuteDataTable(sql).ToListEntity<T>();

}

/// <summary>

/// 根据条件查询得到多个实例 (不分页)

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="condition"></param>

/// <returns></returns>

public static List<T> Get<T>(T condition)

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "SELECT * FROM [" + type.Name + "] WHERE 1=1";

foreach (PropertyInfo item in type.GetProperties())

{

#region 不加条件处理

if (item.GetValue(condition, null) == null)    //null值 不加条件

continue;

if (item.PropertyType.ToString().Contains("Int"))   //整形为 -1 时不加条件

{

if (item.GetValue(condition, null).ToString().Equals("-1"))

{

continue;

}

}

else if (item.PropertyType.ToString().Contains("Decimal"))   //整形为 -1 时不加条件

{

if (item.GetValue(condition, null).ToString().Equals("-1"))

{

continue;

}

}

#endregion

sql += " AND [" + item.Name + "] ";

if (item.PropertyType.ToString().Contains("String") )       //字符串形用模糊查询

sql += " LIKE "+ "'%" + item.GetValue(condition, null) + "%'";

else if (item.PropertyType.ToString().Contains("Date")){    //日期类型

}else{

sql += " = "+ item.GetValue(condition, null) + "";

}

}

#endregion

return DBHelperSQL.ExecuteDataTable(sql).ToListEntity<T>();

}

/// <summary>

/// 根据条件查询得到多个实例 (带分页)

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="condition"></param>

/// <returns></returns>

public static List<T> Get<T>(T condition, int pageIndex, int pageSize, ref int totalCount)

{

#region 生成 SQL 语句

Type type = typeof(T);

string sql = "SELECT TOP " + pageSize + " * FROM [" + type.Name + "] WHERE (ID NOT IN (SELECT TOP " + (pageIndex - 1) * pageSize + " ID FROM [" + type.Name + "] WHERE 1=1 ";

StringBuilder sb = new StringBuilder();

foreach (PropertyInfo item in type.GetProperties())

{

#region 不加条件处理

if (item.GetValue(condition, null) == null)    //null值 不加条件

continue;

if (item.PropertyType.ToString().Contains("Int"))   //整形为 -1 时不加条件

{

if (item.GetValue(condition, null).ToString().Equals("-1"))

{

continue;

}

}

else if (item.PropertyType.ToString().Contains("Decimal"))   //整形为 -1 时不加条件

{

if (item.GetValue(condition, null).ToString().Equals("-1"))

{

continue;

}

}

#endregion

sb.Append(" AND [" + item.Name + "] ");

if (item.PropertyType.ToString().Contains("String"))       //字符串形用模糊查询

sql += " LIKE " + "'%" + item.GetValue(condition, null) + "%'";

else if (item.PropertyType.ToString().Contains("Date"))

{    //日期类型

}

else

{

sql += " = " + item.GetValue(condition, null) + "";

}

}

sql += sb.ToString() + "ORDER BY ID ))  ORDER BY ID ";

//总记录数

string sqlForCount = "SELECT COUNT(*) FROM [" + type.Name + "] WHERE 1=1 " + sb.ToString();

string count = DBHelperSQL.ExecuteString(sqlForCount);

totalCount = string.IsNullOrEmpty(count) ? 0 : int.Parse(count);

#endregion

return DBHelperSQL.ExecuteDataTable(sql).ToListEntity<T>();

}

}

利用反射自动生成SQL语句(仿Linq)的更多相关文章

  1. springboot+mybatis+mysql 利用mybatis自动生成sql语句

    工具和环境 idea,mysql,JDK1.8 效果图如下 结构图如下 java resources sql文件 /* Navicat MySQL Data Transfer Source Serve ...

  2. 使用Excel自动生成sql语句

    在近一段日子里,进入了新的项目组,由于项目需要,经常要将一些Excel表中的数据导入数据库中,以前并没有过多的接触过数据导入与数据处理,对于我来说比较痛苦,今天下午花了几个小时处理数据,但是同事给我提 ...

  3. 使用sqlmetal工具自动生成SQL数据库的Linq类文件

    第一部:找到sqlmetal.exe. 运行cmd. 执行命令 cd C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5 ...

  4. 根据DELTA自动生成SQL语句

    上传客户端的CLIENTDATASET.delta到服务器的clientdataset.data,服务端解析clientdataset的数据生成相应的SQL语句. 相对于直接调用datasetprov ...

  5. 城市联动 - 自动生成SQL语句

    字段比较简单/  如果有需要可以自己定制字段和排序/ 一共二级城市联动, 本人业务需要, 所以就两层, 网上关于三层的挺多, 有需要可以借鉴/ 废话不多说, 先看效果图, 代码在下面 <?php ...

  6. Excel 提供数据 更新或者插入数据 通过函数 自动生成SQL语句

    excel 更新数据 ="UPDATE dbo.yt_vehicleExtensionBase SET yt_purchase_date='"&B2&"' ...

  7. 打开powerDesigner时,创建table对应的自动生成sql语句没有注释

    在创建pdm时由于需要在name列填写的是以后要在表中创建的注释信息,comment中则写的说明信息字数比较多.默认情况下在生成建表sql时不能将name生成注释信息,进行如下设置可以讲name生成注 ...

  8. 利用反射动态构成sql语句

    class Program     {         static void Main(string[] args)         {             People p = new Peo ...

  9. 使用Java注解开发自动生成SQL

    使用注解开发的好处就是减少配置文件的使用.在实际过程中,随着项目越来越复杂,功能越来越多,会产生非常多的配置文件.但是,当配置文件过多,实际维护过程中产生的问题就不容易定位,这样就会徒劳的增加工作量. ...

随机推荐

  1. oracle 表空间 用户

    Oracle创建表空间.创建用户以及授权.查看权限 创建临时表空间 CREATE TEMPORARY TABLESPACE test_temp TEMPFILE 'C:\oracle\product\ ...

  2. Nginx配置一个自签名的SSL证书

    http://www.liaoxuefeng.com/article/0014189023237367e8d42829de24b6eaf893ca47df4fb5e000 要保证Web浏览器到服务器的 ...

  3. hdu 4187 Alphabet Soup

    这题的主要就是找循环节数,这里用找字符串最小覆盖来实现,也就是n-next[n],证明在这http://blog.csdn.net/fjsd155/article/details/6866991 #i ...

  4. Android sqlite cursor的遍历

    查询并获得了cursor对象后,用while(corsor.moveToNext()){}遍历,当corsor.moveToNext()方法调用,如果发现没有对象,会返回false public Li ...

  5. ASP.NET连接数据库并获取数据

    关键词:连接对象的用法SqlConnection,SqlCommand,SqlDataAdapter *数据访问方式的写法 工具/原料 VS SQL SERVER 2012 R2 方法/步骤1: 1. ...

  6. C语言中时间调用处理的相关函数介绍

    asctime(将时间和日期以字符串格式表示) 相关函数:time,ctime,gmtime,localtime 表头文件:#include<time.h> 定义函数:char * asc ...

  7. TCL语言笔记:TCL中的数学函数

    一.TCL数学函数列表 函数名 说明 举例 abs(arg) 取绝对值 set a –10  ; #a=-10 set a [expr abs($a)]; # a=10 acos(arg) 反余弦 s ...

  8. 88. Merge Sorted Array

    题目: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note:You may assume ...

  9. 59. Spiral Matrix II

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  10. 46. Permutations

    题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...