利用反射自动生成SQL语句(仿Linq)
转: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)的更多相关文章
- springboot+mybatis+mysql 利用mybatis自动生成sql语句
工具和环境 idea,mysql,JDK1.8 效果图如下 结构图如下 java resources sql文件 /* Navicat MySQL Data Transfer Source Serve ...
- 使用Excel自动生成sql语句
在近一段日子里,进入了新的项目组,由于项目需要,经常要将一些Excel表中的数据导入数据库中,以前并没有过多的接触过数据导入与数据处理,对于我来说比较痛苦,今天下午花了几个小时处理数据,但是同事给我提 ...
- 使用sqlmetal工具自动生成SQL数据库的Linq类文件
第一部:找到sqlmetal.exe. 运行cmd. 执行命令 cd C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5 ...
- 根据DELTA自动生成SQL语句
上传客户端的CLIENTDATASET.delta到服务器的clientdataset.data,服务端解析clientdataset的数据生成相应的SQL语句. 相对于直接调用datasetprov ...
- 城市联动 - 自动生成SQL语句
字段比较简单/ 如果有需要可以自己定制字段和排序/ 一共二级城市联动, 本人业务需要, 所以就两层, 网上关于三层的挺多, 有需要可以借鉴/ 废话不多说, 先看效果图, 代码在下面 <?php ...
- Excel 提供数据 更新或者插入数据 通过函数 自动生成SQL语句
excel 更新数据 ="UPDATE dbo.yt_vehicleExtensionBase SET yt_purchase_date='"&B2&"' ...
- 打开powerDesigner时,创建table对应的自动生成sql语句没有注释
在创建pdm时由于需要在name列填写的是以后要在表中创建的注释信息,comment中则写的说明信息字数比较多.默认情况下在生成建表sql时不能将name生成注释信息,进行如下设置可以讲name生成注 ...
- 利用反射动态构成sql语句
class Program { static void Main(string[] args) { People p = new Peo ...
- 使用Java注解开发自动生成SQL
使用注解开发的好处就是减少配置文件的使用.在实际过程中,随着项目越来越复杂,功能越来越多,会产生非常多的配置文件.但是,当配置文件过多,实际维护过程中产生的问题就不容易定位,这样就会徒劳的增加工作量. ...
随机推荐
- JS常见排序算法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- hdu 2604 Queuing(动态规划—>矩阵快速幂,更通用的模版)
题目 最早不会写,看了网上的分析,然后终于想明白了矩阵是怎么出来的了,哈哈哈哈. 因为边上的项目排列顺序不一样,所以写出来的矩阵形式也可能不一样,但是都是可以的 //愚钝的我不会写这题,然后百度了,照 ...
- hdu 1162 Eddy's picture(最小生成树,基础)
题目 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<string.h> #include <ma ...
- .net web部署(IIS Express && Nancy Self-Hosting)
http://d.hatena.ne.jp/fkmt5/20140330/1396195246 [1]Nancy Web配置注意事项 添加url:netsh http add urlacl url=h ...
- Thread的第四天学习
线程通信 wait notify synchronized + 同对象 才可 互斥 锁不是放在线程上的,放在共享资源内部的. wait 线程等待 notify 线程唤醒
- lintcode 中等题:A + B Problem A + B 问题
题目: 中等 A + B 问题 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符. 如果 a=1 并且 b=2,返回3 注意 你不需要从输入流读入数据,只需要根据aplusb的两个参数 ...
- 2014-9-17二班----11 web project
http://localhost:8080/rwkj1/indexServlet?name=zhagnsan&pwd=1234 跳 转 http://localhost:8080/rwkj ...
- android MD5
public static String MD5(String str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstan ...
- swift:自动引用计数ARC
Swift自动引用计数:ARC 原文链接:https://numbbbbb.gitbooks.io/-the-swift-programming-language-/content/chapte ...
- Redhat 使用中文安装后更换为英文的设定
vi /etc/sysconfig/i18n将LANG改为LANG=en_US.UTF-8保存退出,重新reboot