using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Web;
using iPortalActive.DB;
using MySql.Data.MySqlClient;

/// <summary>
/// @author:cst@20140612 modified
/// </summary>

namespace CsUtility
{
public enum OperationType
{
Create,
Remove,
Update,
Delete
}

public class OperationFactory
{
public static AbstractDbFactory CreateFactory(OperationType optType)
{
switch (optType)
{
case OperationType.Create:
return new ExecuteFactory();
case OperationType.Remove:
return new QueryFactory();
case OperationType.Update:
return new UpdateFactory();
case OperationType.Delete:
return new DeleteFactory();
default: break;
}
}
}
public abstract class AbstractDbFactory
{

}

public static class MDbMapper<T> where T : class, new()
{
static MDbMapper()
{
}

public static bool Add(T model)
{
string sql = GenerateInsert(model);
MySqlParameter[] paras = GenerateMysqlParamArray(model);
int rowsAffected = DbHelperMySQL.ExecuteSql(sql, paras);
if (rowsAffected > 0)
{
return true;
}
return false;
}

public static bool Update(T model)
{
string sql = GenerateUpdate(model);
MySqlParameter[] paras = GenerateMysqlParamArray(model);
int rowsAffected = DbHelperMySQL.ExecuteSql(sql, paras);
if (rowsAffected > 0)
{
return true;
}
return false;
}

public static bool Delete(T model)
{
string sql = GenerateDelete(model);
MySqlParameter[] paras = GenerateMysqlParamArray(model);
int rowsAffected = DbHelperMySQL.ExecuteSql(sql, paras);
if (rowsAffected > 0)
{
return true;
}
return false;
}

public static IList<T> Query(T model)
{
string sql = GenerateSelect(model);
MySqlParameter[] paras = GenerateMysqlParamArray(model);
DataSet ds = DbHelperMySQL.Query(sql, paras);
return ReflactorHelper<T>.DsToIList(ds);
}

public static int GetCount(T model)
{
throw new NotImplementedException();
}

#region Update Field

private static string GenerateUpdate(T model)
{
if (typeof(T).GetProperty("Id").Equals(null) || typeof(T).GetProperty("id").Equals(null))
{
throw new ArgumentNullException("Id");
}
string sql = "Update " + typeof(T).Name.ToLower() + " set ";
sql += GetWhereString(model, true);
sql += " where id=?Id";
return sql;
}

#endregion

#region Insert Field

private static string GenerateInsert(T model)
{
string sql = "Insert into " + typeof(T).Name.ToLower();
string cols = GetColsString(model, null);
string vals = GetColsString(model, "?");
sql += cols;
sql += "values";
sql += vals;
return sql;
}

private static MySqlParameter[] GenerateMysqlParamArray(T model)
{
PropertyInfo[] ps = model.GetType().GetProperties();
IList<MySqlParameter> list = new List<MySqlParameter>();
for (int i = 0; i < ps.Length; i++)
{
if (ps[i].GetValue(model, null) == null) continue;
list.Add(new MySqlParameter("?" + ps[i].Name,
Convert.ChangeType(ps[i].GetValue(model, null), ps[i].GetValue(model, null).GetType())));
}
var paras = new MySqlParameter[list.Count];
for (int i = 0; i < paras.Length; i++)
{
paras[i] = list[i];
}
return paras;
}

private static string GetColsString(T model, string prefix)
{
PropertyInfo[] ps = typeof(T).GetProperties();
string cols = "(";
for (int i = 0; i < ps.Length; i++)
{
if (ps[i].GetValue(model, null) == null) continue;
cols += (prefix ?? "") + ps[i].Name + ",";
}
cols = cols.TrimEnd(',') + ")";
return cols;
}

#endregion

#region Delete Field

public static string GenerateDelete(T model)
{
string sql = "Delete from " + typeof(T).Name.ToLower() + " where ";
sql += GetWhereString(model, false);
return sql;
}

private static string GetWhereString(T model, bool isUpdate)
{
PropertyInfo[] ps = typeof(T).GetProperties();
string w = isUpdate ? " " : " 1=1 and ";
for (int i = 0; i < ps.Length; i++)
{
if ((isUpdate && ps[i].Name.ToLower().Equals("id")) || ps[i].GetValue(model, null) == null ||
(ps[i].Name.ToLower().Equals("id") && ps[i].GetValue(model, null).Equals(0))) continue;
w += ps[i].Name + "=?" + ps[i].Name + (isUpdate ? "," : " and ");
}
w = isUpdate ? w.TrimEnd(',') : w.Substring(0, w.Length - 4);
return w;
}

#endregion

#region Select Field

public static string GenerateSelect(T model)
{
string sql = "Select * from " + typeof(T).Name.ToLower() + " where ";
sql += GetWhereString(model, false);
return sql;
}

#endregion

#region SelectCount Field

#endregion
}

public static class MReqMapper
{
public static T GetMdl<T>() where T : class, new()
{
HttpRequest request = HttpContext.Current.Request;

var model = new T();

var keys = new string[request.Form.AllKeys.Length + request.QueryString.AllKeys.Length];
request.QueryString.AllKeys.CopyTo(keys, 0);
request.Form.AllKeys.CopyTo(keys, request.QueryString.AllKeys.Length);
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo p in properties)
{
try
{
string val = request.Form[p.Name] ?? request.QueryString[p.Name];
p.SetValue(model, Convert.ChangeType(val, p.PropertyType), null);
}
catch (Exception)
{
}
}
return model;
}
}

public class KeyAttribute : Attribute
{
}

public class Singleton<T> where T : new()
{
public static T Instance = new T();
}

public class ReflactorHelper<T> where T : new()
{
public static IList<T> DsToIList(DataSet ds, int tbIndex)
{
DataTable dt = ds.Tables[tbIndex];
IList<T> list = new List<T>();
DataRowCollection rows = dt.Rows;
PropertyInfo[] pis = typeof(T).GetProperties();
foreach (DataRow dr in rows)
{
T m = DrToModel(dr);
list.Add(m);
}
return list;
}

public static IList<T> DsToIList(DataSet ds)
{
return DsToIList(ds, 0);
}

public static T DrToModel(DataRow row)
{
var m = new T();
foreach (DataColumn col in row.Table.Columns)
{
foreach (PropertyInfo pi in typeof(T).GetProperties())
{
try
{
if (row[pi.Name.ToLower()] != DBNull.Value)
{
pi.SetValue(m, Convert.ChangeType(row[pi.Name.ToLower()], pi.PropertyType), null);
}
}
catch (Exception)
{
}
}
}
return m;
}
}

public enum DbType
{
MsSql,
MySql,
Sqlite
}
public interface IDbHelper
{
int ExecuteSql(string sql, params DbParameter[] paras);
DataSet Query(string sql, params DbParameter[] paras);
object GetSingle(string sql, params DbParameter[] paras);
int GetMaxId(string sql, params DbParameter[] paras);
}

public class Connection
{
private readonly string _db;
public Connection(string db)
{
_db = ConfigurationManager.AppSettings[db];
}
public string Db
{
get { return _db; }
}

}

public class MySqlHelper : IDbHelper
{
private Connection _con;
private MySqlConnection _myCon;
public MySqlHelper(Connection con)
{
_con = con;
_myCon = new MySqlConnection(con.Db);
}

#region IDbHelper 成员

public int ExecuteSql(string sql, params DbParameter[] paras)
{
throw new NotImplementedException();
}

public DataSet Query(string sql, params DbParameter[] paras)
{
throw new NotImplementedException();
}

public object GetSingle(string sql, params DbParameter[] paras)
{
throw new NotImplementedException();
}

public int GetMaxId(string sql, params DbParameter[] paras)
{
throw new NotImplementedException();
}

#endregion
}
}

分享一下我写的.net 2.0的orm类,实现mvc。可以用于webform等环境中,这是orm的原理部分。的更多相关文章

  1. 分享个 之前写好的 android 文件流缓存类,专门处理 ArrayList、bean。

    转载麻烦声明出处:http://www.cnblogs.com/linguanh/ 目录: 1,前序 2,作用 3,特点 4,代码 1,前序  在开发过程中,client 和 server 数据交流一 ...

  2. 分享一个c#写的开源分布式消息队列equeue

    分享一个c#写的开源分布式消息队列equeue 前言 equeue消息队列中的专业术语 Topic Queue Producer Consumer Consumer Group Broker 集群消费 ...

  3. 分享一个自己写的MVC+EF “增删改查” 无刷新分页程序

    分享一个自己写的MVC+EF “增删改查” 无刷新分页程序 一.项目之前得添加几个组件artDialog.MVCPager.kindeditor-4.0.先上几个效果图.      1.首先建立一个数 ...

  4. JAVA串口开发帮助类分享-及写在马年末

    摘要: 在系统集成开发过程中,存在着各式的传输途径,其中串口经常因其安全性高获得了数据安全传输的重用,通过串口传输可以从硬件上保证数据传输的单向性,这是其它介质所不具备的物理条件.下面我就串口java ...

  5. 分享最近抽空写的一个代码生成器,集成EasyDBUtility数据库访问帮助类

    一直想写一个自己的代码生成器,但是因为工作事情多,一直搁置下来,最近下决心终于利用下班时间写完了,现在分享给有需要的朋友,代码生成器集成EasyDBUtility数据库访问帮助类,暂时只支持sqlse ...

  6. 分享一个nodejs写的小论坛

    引言:作为一个前端小菜鸟,最近迷上了node,于是乎空闲时间,为了练练手写了一个node的小社区,关于微信小程序的,欢迎大家批评指导. 项目架构部分 一.前端架构 作为一个写样式也得无聊的前端狮,我偷 ...

  7. 【分享】自己写的一个可空的DateTimePicker控件-附源码

    最近这段时间在重构以前的一个项目,其中有一项就是要把DateTimePicker控件值可空.大家都知道的DateTimePicker值为DateTime类型,DateTime类型值不能等于Null.但 ...

  8. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  9. 手写一个HTTP框架:两个类实现基本的IoC功能

    jsoncat: 仿 Spring Boot 但不同于 Spring Boot 的一个轻量级的 HTTP 框架 国庆节的时候,我就已经把 jsoncat 的 IoC 功能给写了,具体可以看这篇文章&l ...

随机推荐

  1. js双轴柱状图

    <!doctype html><html lang="en"><head> <script type="text/javascr ...

  2. [bzoj3071]N皇后

    哈哈哈水题~ 但是不能一眼看出来的..我想了一个小时?! 题面 Description “国际象棋中,一方的皇后数不能超过5个” 一个N*N的棋盘,任意摆放皇后,最坏情况下最少需要多少个皇后才能保证所 ...

  3. \r \r\n \t的区别

    \n 软回车:      在Windows 中表示换行且回到下一行的最开始位置.相当于Mac OS 里的 \r 的效果.      在Linux.unix 中只表示换行,但不会回到下一行的开始位置. ...

  4. 无法访问hadoop yarn8088端口的解决方法

    1.检查是否正确的启动了resourcemanager服务 若是没有启动,请检查yarn-site-xml配置 2.若是启动了 1.检查客户机和虚拟机之间是否能够相互ping通 2.检查虚拟机防火墙是 ...

  5. Java从后台重定向(redirect)到另一个项目的方法

    (1)通过ModelAndView跳转 @RequestMapping("alipayforward") public ModelAndView alipayforward(Htt ...

  6. shell判断文件是否存在[转]

    原文出处: http://canofy.iteye.com/blog/252289 shell判断文件,目录是否存在或者具有权限 #!/bin/sh myPath="/var/log/htt ...

  7. codility

    // you can also use imports, for example: // import java.util.*; // you can write to stdout for debu ...

  8. 【Python-遇到的Error】AttributeError: 'str' object has no attribute 'input_text'

    学习类的实例化的时候遇到了AttributeError: 'str' object has no attribute 'input_text', 以下是报错的代码及修改正确的代码. class shu ...

  9. Canvas 图片平铺设置

    /** * 图片平铺 */ function initDemo7(){ var canvas = document.getElementById("demo7"); if (!ca ...

  10. unity值得推荐的网址

    免费字体下载网站:http://www.dafont.com/ 免费声音文件下载网站:http://freesound.org/          http://incompetech.com/mus ...