1.解析数据库,得到表的结构
2.使用模版,动态替换
3.生成字符串写到本地
这里主要讲一下如何解析数据库,对于其他的数据库比如,Mysql,Sqlserver,Oracle等数据库等都有对应的sql语句查询出来。
对于这些数据库的解析已经有封装的比较好的解析方式了,比如我的项目中使用的部分就是东软代码生成器开源的类如图,
这一部分可以直接去查看源码,而且注释比较清晰。对于Sqlite他的处理方式就会存在问题,
所以我不得不自己去实现,主要问题在于读取表的结构上,代码如下:
#region 得到表的列的详细信息 GetColumnInfoList(string DbName,string TableName)
/// <summary>
/// 得到数据库里表或视图的列的详细信息
/// </summary>
/// <param name="DbName">库</param>
/// <param name="TableName">表</param>
/// <returns></returns>
public List<ColumnInfo> GetColumnInfoList(string DbName, string TableName)
{
try
{
//if (isdbosp)
//{
// return GetColumnInfoListSP(DbName, TableName);
//}
string strSql = "select * from sqlite_master where type = 'table' and name='" + TableName+"'";
List<ColumnInfo> collist = new List<ColumnInfo>();
SQLiteDataReader reader = ExecuteReader(DbName, strSql);
int n = 1;
while (reader.Read())
{
string CreateTableStr = reader.GetString(4);
int startIndex=CreateTableStr.IndexOf("(");
int endIndex=CreateTableStr.IndexOf(")");
string CoulmnsStr = CreateTableStr.Substring(startIndex+1, endIndex-startIndex-1);
string[] coulmns = CoulmnsStr.Split(',');
foreach(string str in coulmns)
{
ColumnInfo col; col = new ColumnInfo();
col.Colorder = n.ToString();
if (str.Contains("PRIMARY KEY"))
{
col.IsPK = true;
}
else
{
col.IsPK = false;
}
string[] coulmnNameAndType = str.Split(' ');
col.ColumnName = coulmnNameAndType[0].Trim().Replace("\"", "");
col.TypeName = coulmnNameAndType[2].Trim();
collist.Add(col);
n++;
}
}
reader.Close();
return collist;
}
catch (System.Exception ex)
{
throw new Exception("获取列数据失败" + ex.Message);
}
}
其中大部分都是切割字符串。
执行
"select * from sqlite_master where type = 'table' and name='" + TableName+"'";
后返回的结果为:
table|AuditDate|AuditDate|2|CREATE TABLE AuditDate (Time text, OperateType integer, UserName text,EncrypteBox_SrcDisk text,EncrypteBox_SrcName text,EncrypteBox_SrcPath text, EncrypteBox_SrcEx text,EncrypteBox_DesDisk text,EncrypteBox_DesName text,EncrypteBox_DesPath text,EncrypteBox_De*** text,FileName text,FileSrcPath text,FileDesPath text,FileExplain text)
上面是随手粘贴的。。。。
而其中的竖线我发现就是查询结果的分割符,所以可通过后面的建表语句分析出表的结构和字段的类型
然后就可以使用模版来替换了。。。。
下面一篇会将我的模版设计方式