//--------------------------------------------------------------------------
//
// Copyright (c) BUSHUOSX. All rights reserved.
//
// File: Orm4Sqlite.cs
//
// Version:1.0.0.0
//
// Datetime:20170811
//
//--------------------------------------------------------------------------- using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data.SQLite;
using System.Data; namespace BUSHUOSX.Helper
{
public class Orm4Sqlite
{
[Flags]
public enum MemberFlags
{
None = ,
公共字段 = ,
非公字段 = ,
公共属性 = ,
非公属性 = ,
属性可读 = ,
属性可写 = ,
Default = + +
}
public static Dictionary<string, object> GetFiledAndPropetyValue(object obj, HashSet<string> ignore = null, MemberFlags flags = MemberFlags.Default)
{
if (null == obj)
{
return null;
} Dictionary<string, object> tmp = new Dictionary<string, object>(); //var fields = getFields(obj.GetType(), flags);
foreach (var item in getFields(obj.GetType(), flags))
{
if (null != ignore && ignore.Contains(item.Name))
{
continue;
}
tmp[item.Name] = item.GetValue(obj);
} //var properties = getProperties(obj.GetType(), flags);
foreach (var item in getProperties(obj.GetType(), flags))
{
if (null != ignore && ignore.Contains(item.Name))
{
continue;
}
tmp[item.Name] = item.GetValue(obj, null);
} return tmp;
} private static List<MemberInfo> GetFiledsAndPropetys(Type type, HashSet<string> ignore = null, MemberFlags flags = MemberFlags.Default)
{
List<MemberInfo> result = new List<MemberInfo>();
foreach (var item in getFields(type, flags))
{
if (null != ignore && ignore.Contains(item.Name))
{
continue;
}
result.Add(item);
}
foreach (var item in getProperties(type, flags))
{
if (null != ignore && ignore.Contains(item.Name))
{
continue;
}
result.Add(item);
}
return result;
} private static List<PropertyInfo> getProperties(Type type, MemberFlags flags)
{
List<PropertyInfo> tmp = new List<PropertyInfo>();
BindingFlags bfs = BindingFlags.Default; if ((flags & MemberFlags.公共属性) == MemberFlags.公共属性) bfs |= BindingFlags.Public;
if ((flags & MemberFlags.非公属性) == MemberFlags.非公属性) bfs |= BindingFlags.NonPublic;
if (bfs != BindingFlags.Default)
{
bfs |= BindingFlags.Instance | BindingFlags.Static;
var properties = type.GetProperties(bfs);
foreach (var item in properties)
{
if ((flags & MemberFlags.属性可读) == MemberFlags.属性可读)
{
if (!item.CanRead)
{
continue;
}
}
if ((flags & MemberFlags.属性可写) == MemberFlags.属性可写)
{
if (!item.CanWrite)
{
continue;
}
}
tmp.Add(item);
}
}
return tmp;
} private static List<FieldInfo> getFields(Type type, MemberFlags flags)
{
List<FieldInfo> tmp = new List<FieldInfo>();
BindingFlags bfs = BindingFlags.Default;
if ((flags & MemberFlags.公共字段) == MemberFlags.公共字段) bfs |= BindingFlags.Public;
if ((flags & MemberFlags.非公字段) == MemberFlags.非公字段) bfs |= BindingFlags.NonPublic;
if (bfs != BindingFlags.Default)
{
bfs |= BindingFlags.Instance | BindingFlags.Static;
var fileds = type.GetFields(bfs);
tmp.AddRange(fileds);
}
return tmp;
} private static string netType2sqliteType(Type type)
{
if (type.IsValueType)
{
if (type == typeof(float) || type == typeof(double))
{
return "REAL";
}
if (typeof(DateTime) == type)
{
return "DATETIME";
}
return "INTEGER";
} if (typeof(string) == type)
{
return "TEXT";
} return "BLOB";
} public static string GenarateCreateTableSql(Type type, MemberFlags flags = MemberFlags.Default, HashSet<string> ignore = null, Dictionary<string, string> ext = null)
{
Dictionary<string, Type> clms = new Dictionary<string, Type>(); foreach (var item in getFields(type, flags))
{
clms[item.Name] = item.FieldType;
} foreach (var item in getProperties(type, flags))
{
clms[item.Name] = item.PropertyType;
} StringBuilder sb = new StringBuilder();
if (clms.Count != || (null != ext && ext.Count != ))
{
//删除忽略colume
if (null != ignore)
{
foreach (var item in ignore)
{
clms.Remove(item);
}
} sb.AppendFormat(@"CREATE TABLE {0} (", type.Name);
foreach (var item in clms)
{
//sb.AppendFormat(@"{0} {1},", item.Key, item.Value.ToString());//第二项为sqlite数据类型
sb.AppendFormat(@"{0} {1},", item.Key, netType2sqliteType(item.Value));
} if (null != ext)
{
foreach (var item in ext)
{
sb.AppendFormat(@"{0} {1},", item.Key, item.Value);
}
} sb.Replace(",", ")", sb.Length - , );
} return sb.ToString();
} public static string GenarateInsertSql(Type type, MemberFlags flags = MemberFlags.Default, HashSet<string> ignore = null, HashSet<string> ext = null)
{
HashSet<string> columns = new HashSet<string>(); //获取字段
foreach (var item in getFields(type, flags))
{
columns.Add(item.Name);
} //获取属性
foreach (var item in getProperties(type, flags))
{
columns.Add(item.Name);
} if (null != ignore)
{
foreach (var item in ignore)
{
columns.Remove(item);
}
}
if (null != ext)
{
foreach (var item in ext)
{
columns.Add(item);
}
} StringBuilder sql = new StringBuilder(); if ( != columns.Count)
{
sql.AppendFormat(@"INSERT INTO {0} (", type.Name); StringBuilder clms = new StringBuilder();
StringBuilder vals = new StringBuilder();
foreach (var item in columns)
{
clms.AppendFormat("{0},", item);
vals.AppendFormat("@{0},", item);
}
clms.Replace(",", ") VALUES (", clms.Length - , );
vals.Replace(",", ")", vals.Length - , ); sql.Append(clms).Append(vals);
} return sql.ToString();
} public struct ColumnInfo
{
public int cid;
public string name;
public string type;
public bool notnull;
public object dflt_value;
public bool pk;
}
public static List<ColumnInfo> GetColumnInfoFromTable(string conString, string tableName)
{
List<ColumnInfo> result = null;
SQLiteConnection con = new SQLiteConnection(conString);
try
{
SQLiteCommand cmd = new SQLiteCommand(con);
cmd.CommandText = string.Format(@"pragma table_info({0})", tableName); con.Open(); using (var reader = cmd.ExecuteReader())
{
result = new List<ColumnInfo>();
while (reader.Read())
{
result.Add(new ColumnInfo()
{
cid = Convert.ToInt32(reader["cid"]),
name = reader["name"] as string,
notnull = Convert.ToBoolean(reader["notnull"]),
type = reader["type"] as string,
dflt_value = reader["dflt_value"],
pk = Convert.ToBoolean(reader["pk"]),
});
}
}
}
catch (Exception e)
{
//throw;
}
con.Close(); return result;
}
public static List<T> GetDataFromTable<T>(string conString,string selectSql)
where T:new ()
{
List<T> result = null;
SQLiteConnection con = new SQLiteConnection(conString);
try
{
SQLiteDataAdapter sda = new SQLiteDataAdapter(selectSql, con);
DataTable dt = new DataTable();
con.Open();
var i = sda.Fill(dt);
List<PropertyInfo> validProperty = new List<PropertyInfo>();
foreach (var item in dt.Columns)
{
var p = typeof(T).GetProperty(item.ToString());
if (null != p)
{
var x =p.Attributes;
var y = p.GetCustomAttributes(false);
var z = p.GetCustomAttributesData();
validProperty.Add(p);
}
}
result = new List<T>();
foreach (DataRow row in dt.Rows)
{
T t = new T();
foreach (var vp in validProperty)
{
vp.SetValue(t, row[vp.Name], null);
}
result.Add(t);
} dt.Clear();
sda.Dispose();
}
catch (Exception e)
{
}
con.Close();
return result;
}
}
}

orm4sqlite的更多相关文章

随机推荐

  1. SOJ4459 skysky's game(贪心+优先队列)

    天天最近迷上了天天爱消除游戏,现在他觉得这个游戏已经没有意思了.所以他发明一个新的消除游戏.有n堆糖果,每一个糖果有一个重量w,天天每次都选择两个糖果合并为一个糖果,新的糖果的重量等于这两个糖果的重量 ...

  2. csv文件已经python内置csv模块

    csv(Comma Separated Value,即逗号分隔值),文件以纯文本形式存储表格数据(数字和文本).可以用excel打开,并自动将每个逗号隔开的数据作为一列在excel中显示. pytho ...

  3. iframe父页调子页和子页调父页方法

    子页调用父页 window.parent.myChart.resize(); 父页调用子页 $("iframe")[0].contentWindow.myChart.resize( ...

  4. ARM Cortex-A53 Cache与内存的映射关系以及Cache的一致性分析

    ARM Cortex-A53 Cache与内存的映射关系以及Cache的一致性分析 题记:如果文章有理解不对的地方,欢迎大家批评指正,谢谢大家. 摘要:本文以Cortex-A53为例,首先分析Cach ...

  5. git详细使用教程入门到精通(史上最全的git教程)

    Git是分布式版本控制系统,那么它就没有中央服务器的,每个人的电脑就是一个完整的版本库,这样,工作的时候就不 需要联网了,因为版本都是在自己的电脑上.既然每个人的电脑都有一个完整的版本库,那多个人如何 ...

  6. Oracle恢复误删数据

    1.先查出被删除的时间点: select * from flashback_transaction_query where table_name='表名'; 2.根据时间点恢复数据: insert i ...

  7. sudo命令: 在其他用户下操作root用户权限

    一. 场景: 在某个远程服务器 A 上,用 账户1 登陆, 想要在root用户的目录下创建一个 .sh文件,  如果直接 用 touch test.sh 创建,会提示权限不足 此时可以用sudo命令: ...

  8. 给出一个整数,将这个整数中每位上的数字进行反转(JavaScript编程)

    一.问题描述:给出一个整数,将这个整数中每位上的数字进行反转.示例:输入:123,输出321:输入-123,输出-321:输入120,输出-21 二.问题分析与解决: 需要将给出的整数反转,注意示例中 ...

  9. acm--1006

    Problem Description The three hands of the clock are rotating every second and meeting each other ma ...

  10. Redis Sentinel 集群安装 step by step

    一. 准备材料 服务器 IP address 操作系统 位数 Redis 版本   CNT06CAH05 192.168.3.47 CentOS 6.5 x64 Redis-3.2.6 sentine ...