利用反射自动生成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
使用注解开发的好处就是减少配置文件的使用.在实际过程中,随着项目越来越复杂,功能越来越多,会产生非常多的配置文件.但是,当配置文件过多,实际维护过程中产生的问题就不容易定位,这样就会徒劳的增加工作量. ...
随机推荐
- 设置Eclipse智能提示
原地址:http://blog.csdn.net/sz_bdqn/article/details/4956162 今天有点时间,研究了一下MyEclispse的智能感知的功能.刚开始使用它时总是感觉如 ...
- DC-DC升压(BOOST)电路原理
BOOST升压电路中: 电感的作用:是将电能和磁场能相互转换的能量转换器件,当MOS开关管闭合后,电感将电能转换为磁场能储存起来,当MOS断开后电感将储存的磁场能转换为电场能,且这个能量在和 ...
- Android Dock底座应用开发
很多网友可能发现部分Android手机或平板支持底座,目前比较主流的有摩托罗拉系列,中低端的Milestone和Milestone 2代均可以使用充电底座或多媒体底座,网购大概50元左右.而中高端的A ...
- netbean使用技巧
1.让代码智能提示 有些情况下Ctrl+Space这个键被一些输入法占了,我们需要修改一下点击 工具->常规->快捷键映射->找到显示代码完成弹出式菜单->编辑为你喜欢的键就好 ...
- hdu 1175 连连看 (广搜,注意解题思维,简单)
题目 解析见代码 #define _CRT_SECURE_NO_WARNINGS //这是非一般的最短路,所以广搜到的最短的路不一定是所要的路线 //所以应该把所有的路径都搜索出来,找到最短的转折数, ...
- POJ 3070 Fibonacci(矩阵快速幂)
题目链接 题意 : 用矩阵相乘求斐波那契数的后四位. 思路 :基本上纯矩阵快速幂. #include <iostream> #include <cstring> #includ ...
- hdu1151 Air Raid
http://acm.hdu.edu.cn/showproblem.php?pid=1151 增广路的变种2:DAG图的最小路径覆盖=定点数-最大匹配数 #include<iostream> ...
- P1026 犁田机器人
P1026 犁田机器人 时间: 1000ms / 空间: 131072KiB / Java类名: Main 背景 USACO OCT 09 2ND 描述 Farmer John為了让自己从无穷无尽的犁 ...
- lintcode 中等题:interleaving String 交叉字符串
题目 交叉字符串 给出三个字符串:s1.s2.s3,判断s3是否由s1和s2交叉构成. 样例 比如 s1 = "aabcc" s2 = "dbbca" - 当 ...
- ASP.NET连接数据库并获取数据
关键词:连接对象的用法SqlConnection,SqlCommand,SqlDataAdapter *数据访问方式的写法 工具/原料 VS SQL SERVER 2012 R2 方法/步骤1: 1. ...