反射实体类拼接SQL语句
实体类基类:
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语句的更多相关文章
- Java代码实体类生成SQL语句(Java实体类转数据库)
有的时候把数据库删了,如果照着实体类重新创建数据库的话比较麻烦,可以使用这个工具,把代码复制到项目里面设置一下即可把Java代码中的实体类转换为SQL语句输出为一个文件,打开执行命令即可. 下载:ht ...
- c#自定义ORM框架---(泛型&反射&实体类扩展属性<附带通用增、删、查、改>)
该教材主要是运用到泛型.反射和实体类扩展属性 步骤一.建立扩展属性类 实体类扩展属性要继承Attribute基类完成 [AttributeUsage(AttributeTargets.Property ...
- EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的
我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...
- StringBuilder 拼接sql语句比较快
StringBuilder 拼接sql语句比较快StringBuilder strBuilder = new StringBuilder();strSql += "insert into t ...
- ASP.NET实现列表页连接查询 拼接sql语句 绑定grivdView
ASP.NET实现列表页连接查询 拼接sql语句 如图效果: 基本需求:1.当页面第一次加载的时候默认查询一个月时间(或者说是登陆者所属权限的所有数据)的数据绑定到gridView 2.添加查询条件时 ...
- 查询拼接SQL语句,多条件模糊查询
多条件查询,使用StringBuilder拼接SQL语句,效果如下: 当点击按钮时代码如下: private void button1_Click(object sender, EventArgs e ...
- java动态拼接sql语句并且执行时给sql语句的参数赋值
问题 在这里举一个例子,比如我要做一个多条件模糊查询,用户输入的时候有可能输入一个条件,也有可能输入两个条件,这时执行查询的sql语句就不确定了,但可以用动态拼接sql语句来解决这个问题. 解决方法 ...
- java反射获取注解并拼接sql语句
先建两个注解 分别为 Table 和 Column package com.hk.test; import java.lang.annotation.ElementType; import java. ...
- 模拟实现MyBatis中通过SQL反射实体类对象功能
话不多说,直接上干货! package cn.test; import java.lang.reflect.Method; import java.sql.Connection; import jav ...
随机推荐
- 损失函数--KL散度与交叉熵
损失函数 在逻辑回归建立过程中,我们需要一个关于模型参数的可导函数,并且它能够以某种方式衡量模型的效果.这种函数称为损失函数(loss function). 损失函数越小,则模型的预测效果越优.所以我 ...
- Linux平台安装python的psutil包
在Linux平台下,pip install psutil 安装python psutil包,出现下面的错误: psutil/_psutil_common.c:9:20: fatal error: Py ...
- GO-逻辑判断(if,else if,else,switch)
一.if逻辑判断 package main import "fmt" func main() { var a =10; if a>10 { //大括号前不能回车 fmt.Pr ...
- 关于mybtis 使用过程中发生There is no getter for property named 'id' in class 'java.lang.String' 错误
今天在修改一个关于mybtis语句时,偶然发现的一个错误 There is no getter for property named 'id' in class 'java.lang.String' ...
- 【Angular】学习笔记-环境部署、项目建立相关
Angular官网>搭建环境 首先要安装Node.js.官网>Download 一直next就好了. 安装node.js的目的是使用npm这些命令啦 然后这里推荐下载使用git SCM 也 ...
- iTerm2 使用代理
0x00 事件 因为 brew 安装极慢,所以需要 iTerm2 设置代理解决速度问题. 0x01 解决 代理软件开启本地 Http 端口: iTerm 设置代理: $ vim ~/.zshrc # ...
- 命令模式彻底删除oracle实例
步骤一:关闭数据库export ORACLE_SID=bgsp1. sqlplus / as sysdba2. shutdown immediate步骤二:删除实例相关文件1. find $ORACL ...
- postman---postman常用的快捷键
作为一名IT程序猿,不懂一些工具的快捷方式,应该会被鄙视的吧.收集了一些Postman的快捷方式,大家一起动手操作~ 简单操作 操作 mac系统 windows系统 打开新标签 ⌘T Ctrl + T ...
- Red Hat 4.4.7-4上安装glances填大大大坑实录,我的内心是崩溃的!!!
今天的任务是在公司的一台压力测试机上安装一个性能监控工具:glances 因为以前我已经多次安装和使用这个工具,我大意的以为整个过程是这样的: 分分钟搞定完事 然而 我们公司的服务器版本实在是太老了, ...
- ArrayList的输出以及一些问题
//首先需要创建一个ArrayList ArrayList arr=new ArrayList(); //然后往ArrayList里面插入一些值 arr.add("a"); arr ...