实体类基类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Common
{
/// <summary>
/// 实体类基类
/// </summary>
[Serializable]
public abstract class EntityBase
{
/// <summary>
/// 获取主键
/// </summary>
/// <returns></returns>
public abstract string GetPrimaryKey();
/// <summary>
/// 获取INSERT语句
/// </summary>
/// <returns></returns>
public string GetInsertSql()
{
try
{
Type t = this.GetType();
string tableName = t.Name,pKey=this.GetPrimaryKey(),fields=string.Empty,values=string.Empty,temp=null;
foreach (PropertyInfo pi in t.GetProperties())
{
if (!pi.CanWrite) continue;
if (pi.Name.Equals(pKey))
{
continue;
}
temp = GetByTypeStr(pi);
fields += pi.Name + ",";
values += temp + ",";
}
return string.Format("Insert into {0}({1}) Values({2})", tableName, fields.TrimEnd(','), values.TrimEnd(','));
}
catch
{
throw;
}
}
/// <summary>
/// 获取UPDATE语句
/// </summary>
/// <returns></returns>
public string GetUpdateSql()
{
try
{
Type t = this.GetType();
PropertyInfo[] pInfos = t.GetProperties();
string tableName = t.Name, pKey = this.GetPrimaryKey(), str_fields=string.Empty;
int keyIndex = -;
for (int i = ; i < pInfos.Length; i++)
{
if (pInfos[i].Name.Equals(this.GetPrimaryKey()))
{
keyIndex = i;
continue;
}
str_fields += pInfos[i].Name + " = " + GetByTypeStr(pInfos[i]) + ",";
}
return string.Format("Update {0} Set {1} Where {2} = {3}", tableName, str_fields.TrimEnd(','),this.GetPrimaryKey(), GetByTypeStr(pInfos[keyIndex]));
}
catch
{
throw;
}
}
/// <summary>
/// 根据数据类型反射字段值
/// </summary>
/// <param name="pInfo">公共属性</param>
/// <returns></returns>
private string GetByTypeStr(PropertyInfo pInfo)
{
try
{
string result_str = string.Empty;
Type t = pInfo.PropertyType;
object obj = pInfo.GetValue(this, null);
bool valueNull = StringUtil.isNullOrBlank(obj);
if (t == typeof(string))
{
result_str = valueNull ? "null" : "'" + obj.ToString().Replace("--","") + "'";
}
else if (t == typeof(System.Decimal) || t == typeof(System.Int16) || t == typeof(System.Int32) || t == typeof(System.Int64))
{
result_str = t.Name == "Nullable`1"&& valueNull ? "null" : obj.ToString();
//if ()
//{ //}
//else
//{
// result_str = valueNull ? "0" : obj.ToString();
//}
}
else if(t==typeof(DateTime)||t.Name== "Nullable`1")
{
if (valueNull||DateTime.MinValue.Equals(obj)|| t.Name == "Nullable`1")
{
result_str = "null";
}
else
{
result_str = "'"+obj.ToString().Replace("年", "-").Replace("月", "-").Replace("日", "")+"'";
}
}
return result_str;
}
catch
{
throw;
}
}
}
}

实体类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common; namespace Model
{
public class MainModel:EntityBase
{
public decimal id { get; set; }
public string title { get; set; }
public string contents { get; set; }
public string type { get; set; }
public DateTime? date { get; set; }
public string people { get; set; }
public string picurl { get; set; }
/// <summary>
/// 设置主键
/// </summary>
/// <returns></returns>
public override string GetPrimaryKey()
{
return "id";
}
}
}

调用:

             Model.MainModel model = new Model.MainModel();
model.title = context.Request.Form["txtTitle"];
model.people = context.Request.Form["txtName"];
model.contents = context.Request.Form["txtContent"];
string resSql = model.GetInsertSql();

反射实体类拼接SQL语句的更多相关文章

  1. Java代码实体类生成SQL语句(Java实体类转数据库)

    有的时候把数据库删了,如果照着实体类重新创建数据库的话比较麻烦,可以使用这个工具,把代码复制到项目里面设置一下即可把Java代码中的实体类转换为SQL语句输出为一个文件,打开执行命令即可. 下载:ht ...

  2. c#自定义ORM框架---(泛型&反射&实体类扩展属性<附带通用增、删、查、改>)

    该教材主要是运用到泛型.反射和实体类扩展属性 步骤一.建立扩展属性类 实体类扩展属性要继承Attribute基类完成 [AttributeUsage(AttributeTargets.Property ...

  3. EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的

    我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...

  4. StringBuilder 拼接sql语句比较快

    StringBuilder 拼接sql语句比较快StringBuilder strBuilder = new StringBuilder();strSql += "insert into t ...

  5. ASP.NET实现列表页连接查询 拼接sql语句 绑定grivdView

    ASP.NET实现列表页连接查询 拼接sql语句 如图效果: 基本需求:1.当页面第一次加载的时候默认查询一个月时间(或者说是登陆者所属权限的所有数据)的数据绑定到gridView 2.添加查询条件时 ...

  6. 查询拼接SQL语句,多条件模糊查询

    多条件查询,使用StringBuilder拼接SQL语句,效果如下: 当点击按钮时代码如下: private void button1_Click(object sender, EventArgs e ...

  7. java动态拼接sql语句并且执行时给sql语句的参数赋值

    问题 在这里举一个例子,比如我要做一个多条件模糊查询,用户输入的时候有可能输入一个条件,也有可能输入两个条件,这时执行查询的sql语句就不确定了,但可以用动态拼接sql语句来解决这个问题. 解决方法 ...

  8. java反射获取注解并拼接sql语句

    先建两个注解 分别为 Table 和 Column package com.hk.test; import java.lang.annotation.ElementType; import java. ...

  9. 模拟实现MyBatis中通过SQL反射实体类对象功能

    话不多说,直接上干货! package cn.test; import java.lang.reflect.Method; import java.sql.Connection; import jav ...

随机推荐

  1. DNS解析服务结构图

    1.DNS(domain name system) 域名 <==> IP地址 DNS解析过程:

  2. 【koa2】用户注册、登录校验与加盐加密

    加密与解密 先介绍一下关于服务端用户名跟密码的存储状态,我们知道当前端在注册一个新用户时,会在表单内填入用户名和密码,并通过post请求提交到服务器,服务器再把用户名和密码从ctx.request.b ...

  3. 【转载】作为Android开发者,你真的熟悉Activity吗?

    学过android的人都知道,activity是最常用的四大组件之一,但你真的了解透彻activity了吗?接下来,本人将从activity的正常和异常生命周期.启动模式.IntentFilter匹配 ...

  4. ABP入门教程3 - 解决方案

    点这里进入ABP入门教程目录 创建项目 点这里进入ABP启动模板 如图操作,我们先生成一个基于.NET Core的MPA(多页面应用).点击"Create my project!" ...

  5. iptables 从入门到应用

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://powermichael.blog.51cto.com/12450987/1952 ...

  6. Oracle 11g DATAGUARD 同步延时监控脚本

    转自 https://blog.51cto.com/8858975/1401988监控脚本(注:这里没用Sendmail工具发送邮件,如果用的话需要修改)$cat check_oracle_dg_de ...

  7. django之ORM字段及参数

    目录 ORM字段及参数 orm常用字段 字段合集 自定义char字段 字段参数 外键字段的参数 ORM字段及参数 orm常用字段 字段名 说明 AutoField 如果自己没有定义主键id,djang ...

  8. nvidia quadro m5000 驱动安装 - 1804 ubuntu; nvidia-smi topo --matrix 查看gpu拓扑;nvidia-smi命令使用;

    查看GPU型号: lspci | grep -i nvidia 驱动安装: https://www.nvidia.cn/Download/index.aspx?lang=cn 下载对应版本的驱动驱动程 ...

  9. Fiddler 过滤图片

    fiddler过滤无用图片操作步骤1.在右侧Filters中勾选 Hide if URL contains 2.在 Hide if URL contains 中加入下面一行过滤图片代码 REGEX:( ...

  10. python读写Excel方法(xlwt和xlrd)

    在我们做平常工作中都会遇到操作excel,那么今天写一篇,如何通过python操作excel,当然python操作excel的库有很多,比如pandas,xlwt/xlrd,openpyxl等,每个库 ...