系列文章
C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709
C#底层库–数据库访问帮助类(MySQL版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379
C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871
C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161
C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445
C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766
C#底层库–随机数生成类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812
C#RegexHelper正则表达式帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286
前言
本文将新增一个专栏–底层库,分享编程过程中常用的方法函数。我们将这些常用的方法函数,进行封装,反复测试,形成通用化类库。
方便研发人员,只需要几行代码就可以使用它,解决一些难点问题。
底层库的封装涉及到:数据库操作、加解密算法、日志记录、网络通信、邮件发送、文件操作、参数保存、Excel导入导出等等,持续关注本专栏吧。大家有任何问题,也可以评论区反馈,私信我。
一、底层库介绍
自动代码生成器
二、底层库源码
2.1代码模板
根据数据库表,创建Model、BLL、DAL代码。
创建类CodeFactory.cs,复制以下代码。
using CreateCode.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreateCode.BLL
{
public static class CodeFactory
{
#region 创建Model
public static void CreateModel(string a_strNameSpace, string a_strTableName, string a_strDirPath)
{
StringBuilder l_sb = new StringBuilder();
l_sb.AppendLine("using System;");
l_sb.AppendLine();
l_sb.AppendLine($"namespace {a_strNameSpace}.Model");
l_sb.AppendLine("{");
l_sb.AppendLine(@" /// </summary>");
l_sb.AppendLine($@" /// Model层 {a_strTableName}(以下代码由工具自动生成,有错误请反馈)");
l_sb.AppendLine(@" /// </summary>");
l_sb.AppendLine($" public class {Utils.ToUpperFirstword(a_strTableName)}");
l_sb.AppendLine(" {");
var dt = DBService.GetDataColumns(a_strTableName).Tables["ds"];
foreach (DataRow dr in dt.Rows)
{
string l_strType = Utils.SqlTypeToCType(dr["data_type"].ToString());
l_sb.Append($" public {l_strType} {dr["column_name"].ToString()}").Append(" { get; set; }").AppendLine();
}
l_sb.AppendLine(" }");
l_sb.AppendLine("}");//命名空间结束括号
string l_strFilePath = Path.Combine(a_strDirPath, "Model", $"{a_strTableName}Model.cs");
Utils.FileWrite(l_sb.ToString(), l_strFilePath);
}
#endregion
#region 创建DAL
public static void CreateDAL(string a_strNameSpace, string a_strTableName, string a_strDirPath)
{
//去除自增列
//string colsNotAutoKey = GetColumns(a_dtTable).Where(m => m != txt.AutoAdd.text.trim()).toarry();
//l_sb.AppendLine(" DBHelperMySQL sh = new DBHelperMySQL();");
//l_sb.AppendLine($" {string.Join(",", l_strs)} values");
//l_sb.AppendLine($" ({string.Join(",", l_strs.Select(m => "@" + m))}\", values");
StringBuilder l_sb = new StringBuilder();
l_sb.AppendLine("using System;");
l_sb.AppendLine("using System.Collections.Generic;");
l_sb.AppendLine("using System.Data;");
l_sb.AppendLine("using CreateCode.DAL;");
l_sb.AppendLine();
l_sb.AppendLine(@"/// </summary>");
l_sb.AppendLine($@"/// DAL层 {a_strTableName}(以下代码由工具自动生成,有错误请反馈)");
l_sb.AppendLine(@"/// </summary>");
l_sb.AppendLine($"namespace {a_strNameSpace}.DAL"); //命名空间
l_sb.AppendLine("{"); //命名空间
l_sb.AppendLine($" public class {Utils.ToUpperFirstword(a_strTableName)}");
l_sb.AppendLine(" {");
l_sb.AppendLine(" /// <summary>");
l_sb.AppendLine(" /// 执行语句(带事务回滚机制):插入、修改、删除");
l_sb.AppendLine(" /// 使用条件:需引入封装类DBHelperMySQL.cs、MakeSQLHelper.cs");
l_sb.AppendLine(" /// </summary>");
l_sb.AppendLine(" /// <returns>返回执行行数</returns>");
l_sb.AppendLine(" public int ExecuteSql()");
l_sb.AppendLine(" {");
l_sb.AppendLine(" List<T> list = new List<T>();");
l_sb.AppendLine(" List<String> SQLTextList = new List<string>();");
l_sb.AppendLine(" SQLTextList.Clear();");
l_sb.AppendLine("");
l_sb.AppendLine(" //1、插入语句");
l_sb.AppendLine(" MakeSQLHelper MakeSQL = new MakeSQLHelper();");
l_sb.AppendLine($" string l_strInsertSql = MakeSQL.CreateInsertSQLBuilder({a_strTableName}, list);");
l_sb.AppendLine(" SQLTextList.Add(l_strInsertSql);");
l_sb.AppendLine("");
l_sb.AppendLine(" //2、修改语句");
l_sb.AppendLine(" string l_strModifySql = \"update \";");
l_sb.AppendLine(" SQLTextList.Add(l_strModifySql);");
l_sb.AppendLine("");
l_sb.AppendLine(" //3、删除语句");
l_sb.AppendLine(" string l_strDeleteSql = \"\";");
l_sb.AppendLine(" SQLTextList.Add(l_strDeleteSql);");
l_sb.AppendLine("");
l_sb.AppendLine(" }");
l_sb.AppendLine("");
l_sb.AppendLine(" /// <summary>");
l_sb.AppendLine(" /// 查询语句");
l_sb.AppendLine(" /// 使用条件:需引入封装类DBHelperMySQL.cs");
l_sb.AppendLine(" /// </summary>");
l_sb.AppendLine(" /// <returns>DataTable</returns>");
l_sb.AppendLine(" public DataTable GetData()");
l_sb.AppendLine(" {");
l_sb.AppendLine(" string l_strSql = \"select * from tb\";");
l_sb.AppendLine(" return DBHelperMySQL.Query(l_strSql).Tables[0];");
l_sb.AppendLine(" }");
l_sb.AppendLine(" }");
l_sb.AppendLine("}");
string l_strFilePath = Path.Combine(a_strDirPath, "DAL", $"{a_strTableName}DAL.cs");
Utils.FileWrite(l_sb.ToString(), l_strFilePath);
}
#endregion
#region 创建BLL
public static void CreateBLL(string a_strNameSpace, string a_strTableName, string a_strDirPath)
{
StringBuilder l_sb = new StringBuilder();
l_sb.AppendLine("using System;");
l_sb.AppendLine("using System.Collections.Generic;");
l_sb.AppendLine("using System.Data;");
l_sb.AppendLine();
l_sb.AppendLine($"namespace {a_strNameSpace}.BLL");
l_sb.AppendLine("{");
l_sb.AppendLine($" public class {Utils.ToUpperFirstword(a_strTableName)}");
l_sb.AppendLine(" {");
l_sb.AppendLine(" }");
l_sb.AppendLine("}");
string l_strFilePath = Path.Combine(a_strDirPath, "BLL", $"{a_strTableName}BLL.cs");
Utils.FileWrite(l_sb.ToString(), l_strFilePath);
}
#endregion
}
}
2.2数据库查询
查询数据库中的所有表、所有表的列。
创建类DBOperation.cs,复制以下代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreateCode.DAL
{
public class DBService
{
/// <summary>
/// 查询所有库
/// </summary>
/// <returns></returns>
public static DataTable GetDataBases()
{
string l_strSql = "SHOW DATABASES";
return MySQLHelper.ShowDataBases(l_strSql).Tables[0] ;
}
/// <summary>
/// 查询表
/// </summary>
/// <returns></returns>
public static DataTable GetDataTables()
{
string l_strSql = $@"select table_name from information_schema.tables
where table_schema='{MySQLHelper.dataBaseName}'
order by table_name";
return MySQLHelper.Query(l_strSql).Tables[0];
}
/// <summary>
/// 查询列
/// </summary>
/// <returns></returns>
public static DataSet GetDataColumns(string a_strTableName)
{
string l_strSql = $@"select column_name,data_type from information_schema.columns
WHERE TABLE_SCHEMA = '{MySQLHelper.dataBaseName}' AND TABLE_NAME = '{a_strTableName}'";
return MySQLHelper.Query(l_strSql);
}
}
}
三、调用方法
3.1选择数据库,进行所有表查询。
private void cbo_DataBases_SelectedIndexChanged(object sender, EventArgs e)
{
this.lBC_Left.Items.Clear();
this.lBC_Right.Items.Clear();
if (this.cbo_DataBases.Text.Contains("请选择"))
{
return;
}
else
{
MySQLHelper.dataBaseName = this.cbo_DataBases.Text.Trim();//修改库
DataTable l_dtTables = DBService.GetDataTables();
foreach (DataRow dr in l_dtTables.Rows)
{
this.lBC_Left.Items.Add(dr["table_name"].ToString());
}
}
}
3.2 点击按钮,生成代码模板文件
private void sbtn_Create_Click(object sender, EventArgs e)
{
string l_strNameSpace = text_nameSpace.Text.Trim();
dxErrorProvider1.ClearErrors();
if (this.lBC_Right.Items.Count <= 0)
{
XtraMessageBox.Show("请选择要生成表!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(l_strNameSpace))
{
dxErrorProvider1.SetError(text_nameSpace, "命名空间不能为空!"); //必须为dev控件
text_nameSpace.Focus();
return;
}
if (!(cb_Models.Checked || cb_DAL.Checked || cb_Bll.Checked))
{
XtraMessageBox.Show("生成策略至少勾选一个!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "选择代码保存目录";
fbd.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
DialogResult dialogResult = fbd.ShowDialog();
if (dialogResult == DialogResult.OK)
{
string l_strDir = Path.Combine(fbd.SelectedPath, l_strNameSpace);
foreach (string l_strTableName in lBC_Right.Items)
{
if (cb_Models.Checked)
{
CodeFactory.CreateModel(l_strNameSpace, l_strTableName, l_strDir);
}
if (cb_DAL.Checked)
{
CodeFactory.CreateDAL(l_strNameSpace, l_strTableName, l_strDir);
}
if (cb_Bll.Checked)
{
CodeFactory.CreateBLL(l_strNameSpace, l_strTableName, l_strDir);
}
}
XtraMessageBox.Show("代码生成成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(l_strDir);
}
}
三、程序运行效果