转: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. 果盟广告SDK

    // // GuomobWallView.h // GuoMobWallSample // // Created by keyrun on 14-1-21. // Copyright (c) 2014 ...

  2. HDU4670 Cube number on a tree 树分治

    人生的第一道树分治,要是早点学我南京赛就不用那么挫了,树分治的思路其实很简单,就是对子树找到一个重心(Centroid),实现重心分解,然后递归的解决分开后的树的子问题,关键是合并,当要合并跨过重心的 ...

  3. HDU 2489 Minimal Ratio Tree(dfs枚举+最小生成树)

    想到枚举m个点,然后求最小生成树,ratio即为最小生成树的边权/总的点权.但是怎么枚举这m个点,实在不会.网上查了一下大牛们的解法,用dfs枚举,没想到dfs还有这么个作用. 参考链接:http:/ ...

  4. JsRender系列demo(7)compline

    <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery.j ...

  5. QTP重要功能总结

    以下为QTP最应掌握的.最常用的功能(以下仅提供菜单入口,其他还有很多入口,但功能都是一样的) 1.QTP上方菜单栏->Tools->Object Spy(对象探测器)----多个入口 功 ...

  6. Git命令参考手册(转)

    git init # 初始化本地git仓库(创建新仓库) git config --global user.name "xxx" # 配置用户名 git config --glob ...

  7. JS操作Radio与Select

    //radio的chang事件,以及获取选中的radio的值 $("input[name=radioName]").on("change", function( ...

  8. 在sklearn上读取人脸数据集保存图片到本地

    程序如下: # -*- coding: utf-8 -*- """ Created on Sat Oct 31 17:36:56 2015 ""&qu ...

  9. 被忽略却很有用的html标签

    <base>标签  作用:标签为页面中所有链接指定默认链接地址或链接目标.有时候我们需要让首页的链接全部在新窗口中打开,我们一般会这样写链接,而使用这个标签就能一下搞定了! 属性:Href ...

  10. 【nginx运维基础(6)】Nginx的Rewrite语法详解

    概述 重写URL是非常有用的一个功能,因为它可以让你提高搜索引擎阅读和索引你的网站的能力:而且在你改变了自己的网站结构后,无需要求用户修改他们的书签,无需其他网站修改它们的友情链接:它还可以提高你的网 ...