sqlite3 根据实体自动生成建表语句
2024-09-21 14:00:41
public class BuildSqlTool
{
public static string GetCreateTableSql(object t)
{
//CREATE TABLE "StructureView2"("Id" INTEGER PRIMARY KEY AUTOINCREMENT , "IdxNo" VARCHAR, "Name" VARCHAR, "Content" VARCHAR, "Price" FLOAT, "Order" INTEGER)
string sqlStr = "CREATE TABLE \"{0}\" ({1})";
Type type = t.GetType();
PropertyInfo[] pi = type.GetProperties();
string sqlFormat = "\"{0}\" {1}";
string sqlStr2 = "";
foreach (PropertyInfo p in pi)
{
string name=p.Name;
object[]abc=p.GetCustomAttributes(true);
if (name.ToLower()=="id")
{
sqlStr2 += string.Format(sqlFormat, "Id", "INTEGER PRIMARY KEY AUTOINCREMENT");
}
else
{
sqlStr2 +=","+string.Format(sqlFormat, name, SqlType(p));
}
}
return string.Format(sqlStr, GetTableName(type), sqlStr2);
} static string GetTableName(Type type)
{
var tableAttr = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();
return tableAttr != null ? tableAttr.Name : type.Name;
} static string SqlType(PropertyInfo p)
{
Type clrType = p.PropertyType;
if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32))
{
return "integer";
}
else if (clrType == typeof(UInt32) || clrType == typeof(Int64))
{
return "bigint";
}
else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal))
{
return "float";
}
else if (clrType == typeof(String))
{
return "varchar";
//int len = MaxStringLength(p);
//return "varchar(" + len + ")";
}
else if (clrType == typeof(DateTime))
{
return "datetime";
}
else if (clrType.IsEnum)
{
return "integer";
}
else if (clrType == typeof(byte[]))
{
return "blob";
}
else if (clrType == typeof(Guid))
{
return "varchar(36)";
}
else
{
throw new NotSupportedException("Don't know about " + clrType);
}
} int MaxStringLength(PropertyInfo p)
{
var attrs = p.GetCustomAttributes(typeof(MaxLengthAttribute), true);
if (attrs.Length > 0)
{
return ((MaxLengthAttribute)attrs[0]).Value;
}
else
{
return 140;
}
}
}
主要目的是为了减少见表,同理,可自动生成orm的sql
使用范例
// 获取当前程序集
Assembly assembly = Assembly.GetExecutingAssembly();
// 创建类的实例,返回为 object 类型类的完全限定名(即包括命名空间)
object obj = assembly.CreateInstance("ConstructionBudget.Model.VModel1");
string sql = BuildSqlTool.GetCreateTableSql(obj);
最新文章
- 基于Bootstrap里面的Button dropdown打造自定义select
- spark streaming 接收 kafka 数据java代码WordCount示例
- js 表格实现
- 回传数据startActivityForResult()
- wampserver You don't have permission to access / on this server. 解决 方法(转,正好碰到这样的事情了就转下来)
- STATIC::含义
- Spring各jar包的作用(转载)
- 一个高级PHP工程师所应该具备的
- DEV GridControl 鼠标单击事件
- Django Form Media 阅读笔记
- tt程序分析(一)
- OS X第三方类库管理工具cocoapods入门
- C++ STL基本容器使用
- 使用 C# 代码实现拓扑排序
- 学习笔记70—Photoshop画齿轮
- BZOJ4818 [SDOI2017] 序列计数 【矩阵快速幂】
- #python str.format 方法被用于字符串的格式化输出。
- jmeter 获取执行脚本的路径
- 一份可以发布jar包到MAVEN中央仓库的POM
- 自定义两行可左右滑动的GridView