热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

简单三层代码生成器(C#)(传智播客整理)

界面代码【Form1】usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;using

界面

代码

【Form1】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace 代码生成器
{public partial class Form1 : Form{public Form1(){InitializeComponent();}//for(int i&#61;0;i<4;i&#43;&#43;){//}string kongge1 &#61; "\t";string kongge2 &#61; "\t\t";string kongge3 &#61; "\t\t\t";string kongge4 &#61; "\t\t\t\t";StringBuilder SB &#61; new StringBuilder();#region 把数据库类型转化为.net类型private static string ToNetType(string dataType){switch (dataType){case "int":return "int";break;case "nvarchar":case "varchar":case "char":case "nchar":return "string";case "bit":return "bool";case "datetime":return "DateTime";default:return "object";}} #endregion#region 数据库连接操作public DataTable ExecuteDataTable(string cmdText, params SqlParameter[] parameters)//不能写成static{using (SqlConnection conn &#61; new SqlConnection(txtConnStr.Text)){//WhetherCon(txtConnSr.Text);//待优化 /************此处写等待用户输入的代码********************/conn.Open();using (SqlCommand cmd &#61; conn.CreateCommand()){cmd.CommandText &#61; cmdText;cmd.Parameters.AddRange(parameters);DataTable dt &#61; new DataTable();SqlDataAdapter adapter &#61; new SqlDataAdapter(cmd);adapter.Fill(dt);return dt;}}} #endregion#region "连接"按钮事件private void btnConnect_Click(object sender, EventArgs e){DataTable dt &#61; ExecuteDataTable("select * from information_schema.tables");foreach (DataRow row in dt.Rows){string tablename &#61; (string)row["TABLE_NAME"];clbFile.Items.Add(tablename);}}#endregion#region "生成"按钮事件&#xff1b;生成文件选项private void btnGo_Click(object sender, EventArgs e){foreach (string tablename in clbFile.CheckedItems)//遍历&#xff0c;获得用户所勾选的表的名字{if (checkBox1.Checked &#61;&#61; true)/*★★*/{CreateModel(tablename);//生成modelSB.AppendLine("模型层生成完成\r\n");}if (checkBox2.Checked &#61;&#61; true){CreateDAL(tablename);//生成DALSB.AppendLine("数据访问层生成完成\r\n");}if (checkBox3.Checked &#61;&#61; true){CreateBLL(tablename);//生成BLLSB.AppendLine("业务逻辑层生成完成\r\n");}txtShow.Text&#61;SB.ToString();}}#endregion #region 生成Model///

/// 生成Model/// /// private void CreateModel(string tablename){DataTable dtCols &#61; ExecuteDataTable("select * from information_schema.columns where table_name&#61;&#64;tablename", new SqlParameter("tablename", tablename));//得到选中的表StringBuilder sb &#61; new StringBuilder();//用来拼接字符串的对象sb.AppendLine("using System;");sb.AppendLine("using System.Collections.Generic;");sb.AppendLine("using System.Linq;");sb.AppendLine("using System.Text;");sb.AppendLine("using System.Threading.Tasks;\r\n");sb.AppendLine("namespace " &#43; textBox1.Text.Trim()&#43; ".Model{");sb.AppendLine(kongge1&#43;"class "&#43;tablename);sb.AppendLine(kongge1&#43;"{");foreach(DataRow row in dtCols.Rows)/*★参数中数据库类型和.net的数据类型之间的转换*///遍历每行&#xff0c;得到要用的参数&#xff0c;并赋给其它变量{string colName &#61; (string)row["Column_Name"];string dataType &#61; (string)row["Data_Type"];string netType &#61; ToNetType(dataType);sb.AppendLine(kongge2 &#43; "public" &#43; " " &#43; netType &#43; " " &#43; colName &#43; "{get;set;}");//MessageBox.Show((string)row["Column_Name"] &#43; (string)row["Data_Type"]);}sb.AppendLine(kongge1&#43;"}");sb.AppendLine( "}");File.WriteAllText(textBox2.Text &#43; &#64;"\" &#43; tablename &#43; "Model.cs", sb.ToString());} #endregion/*得到数据库表列名的第二种方式&#xff1a;*************************************///private static string[] GetColumnNames(DataTable table)//{// string[] colnames &#61; new string[table.Columns.Count];// for (int i &#61; 0; i &#39;Id&#39; and table_name&#61;&#64;tablename", new SqlParameter("tablename", tablename));string[] colnames &#61; new string[dtCols.Rows.Count];for (int i &#61; 0; i &#39;Id&#39; and table_name&#61;&#64;tablename", new SqlParameter("tablename", tablename));string[] colnames &#61; new string[dtCols.Rows.Count];for (int i &#61; 0; i /// 生成DAL&#xff1a;CreateDAL/// /// private void CreateDAL(string tablename){DataTable dtCols &#61; ExecuteDataTable("select * from information_schema.columns where Column_Name<>&#39;Id&#39; and table_name&#61;&#64;tablename", new SqlParameter("tablename", tablename));string[] parameters &#61; GetParametersFromTable(tablename);string[] colnames &#61; getTableFromDataBase(tablename);StringBuilder sb &#61; new StringBuilder();/************命名空间***************/sb.AppendLine("using System;");sb.AppendLine("using System.Collections.Generic;");sb.AppendLine("using System.Data;");sb.AppendLine("using System.Data.SqlClient;");sb.AppendLine("using System.Linq;");sb.AppendLine("using System.Text;");sb.AppendLine("using System.Threading.Tasks;");sb.AppendLine("using System.Windows.Forms;");sb.AppendLine("using " &#43; textBox1.Text.Trim() &#43; ".Model;\r\n");sb.AppendLine("namespace " &#43; textBox1.Text.Trim() &#43; ".DAL{");sb.AppendLine(kongge1&#43;"class "&#43;tablename&#43;"DAL{");/************AddNew()方法***************/sb.AppendLine(kongge2&#43;"public int AddNew(" &#43; tablename &#43; " model){");sb.Append(kongge3&#43;"object obj &#61; SqlHelper.ExecuteScalar(");sb.Append("\"intsert into " &#43; tablename &#43; "(" &#43; string.Join(",", colnames) &#43; ") values (" &#43; string.Join(",", parameters) &#43; ");select &#64;&#64;identity\"");/*&#64;只能转义“\”,这里必须用“\”来转义*//*▲string.Join方法&#xff1a;第一个参数是分隔符&#xff1b;第二个参数参数字符串*//*▲拼&#xff1a;“(Age,Name) values(&#64;Age,&#64;Name)”形式的参数*///拼参数foreach (string colname in colnames){sb.Append(",new SqlParameter(\"" &#43; colname &#43; "\",model." &#43; colname &#43; ")");}sb.AppendLine(");");sb.AppendLine(kongge3&#43;"return Convert.ToInt32(obj);");sb.AppendLine(kongge2&#43;"}");/************拼Delete()方法***************/sb.AppendLine(kongge2&#43;"public int Delete(int id){");sb.Append(kongge3&#43;"return SqlHelper.ExecuteNonQuery(");sb.Append("\"delete from " &#43; tablename &#43; " where id&#61;&#64;id\",new SqlParameter(");sb.AppendLine("\"id\",id));");//★字符串的拼接&#xff0c;这里有点麻烦要注意sb.AppendLine(kongge2&#43;"}");/************拼Update()方法***************//*★拼&#xff1a;“Name&#61;&#64;Name,Age&#61;&#64;Age”形式的参数列表******/sb.AppendLine(kongge2&#43;"public int Update(" &#43; tablename &#43; " model){");sb.Append(kongge3&#43;"return SqlHelper.ExecuteNonQuery").Append("(\"update " &#43; tablename &#43; " set ");foreach (string colname in colnames){sb.Append(colname &#43; "&#61;&#64;" &#43; colname &#43; ",");}sb.Append("where id&#61;&#64;id\"");foreach (string colname in colnames){sb.Append(",new SqlParameter(\"" &#43; colname &#43; "\",model." &#43; colname &#43; ")");}sb.AppendLine(");");sb.AppendLine(kongge2&#43;"}");sb.AppendLine("\n");/************拼Get()方法***************///▲where后面有bug&#xff0c;有个逗号不好处理sb.AppendLine(kongge2&#43;"public " &#43; tablename &#43; " Get(int id){");sb.AppendLine(kongge3&#43;"DataTable dt &#61; SqlHelper.ExecuteDataTable(\"select * from " &#43; tablename &#43; " where id&#61;&#64;id\",new SqlParameter(\"id\",id));");sb.AppendLine(kongge3&#43;"if (dt.Rows.Count <&#61; 0) {return null;}");sb.AppendLine(kongge3&#43;"else if(dt.Rows.Count&#61;&#61;1){");sb.AppendLine(kongge4&#43;tablename &#43; " model&#61;new " &#43; tablename &#43; "();");sb.AppendLine(kongge4&#43;"DataRow row &#61; dt.Rows[0];");foreach (DataRow row in dtCols.Rows){string colName &#61; (string)row["Column_Name"];string dataType &#61; (string)row["Data_Type"];string netType &#61; ToNetType(dataType);sb.AppendLine(kongge4&#43;"model." &#43; colName &#43; "&#61;(" &#43; netType &#43; ")row[\"" &#43; colName &#43; "\"];");}sb.AppendLine(kongge4&#43;"return model;");sb.AppendLine(kongge3&#43;"}else{");sb.AppendLine(kongge4&#43;"throw new Exception(\"出现多条id值相同的数据\");");sb.AppendLine(kongge3&#43;"}");sb.AppendLine(kongge2&#43;"}");sb.AppendLine(kongge1&#43;"}");sb.AppendLine("}");//MessageBox.Show(sb.ToString());File.WriteAllText(textBox2.Text &#43; &#64;"\" &#43; tablename &#43; "DAL.cs", sb.ToString());} #endregion#region Default生成的BLLprivate void CreateBLL(string tablename){StringBuilder sb &#61; new StringBuilder();sb.AppendLine("using System;");sb.AppendLine("using System.Collections.Generic;");sb.AppendLine("using System.Data;");sb.AppendLine("using System.Data.SqlClient;");sb.AppendLine("using System.Linq;");sb.AppendLine("using System.Text;");sb.AppendLine("using System.Threading.Tasks;");sb.AppendLine("using " &#43; tablename &#43; ".DAL;");sb.AppendLine("using " &#43; tablename &#43; ".Model;\r\n");sb.AppendLine("namespace " &#43; textBox1.Text.Trim()&#43; ".BLL;{");sb.AppendLine(kongge1&#43;"class " &#43; tablename &#43; "BLL{");sb.AppendLine(kongge2&#43;"pulic int AddNew(" &#43; tablename &#43; " model){");sb.AppendLine(kongge3&#43;"return new " &#43; tablename &#43; "DAL().AddNew(model);");sb.AppendLine(kongge2&#43;"}");sb.AppendLine(kongge2&#43;"pulic int Delete(int id){");//假设Id是主键且必须有的sb.AppendLine(kongge3&#43;"return new " &#43; tablename &#43; "DAL().Delete(id);");sb.AppendLine(kongge2&#43;"}");sb.AppendLine(kongge2&#43;"pulic int Update(" &#43; tablename &#43; " model){");sb.AppendLine(kongge3&#43;"return new " &#43; tablename &#43; "DAL().Update(model);");sb.AppendLine(kongge2&#43;"}");sb.AppendLine(kongge2&#43;"pulic int Get(int id){");sb.AppendLine(kongge3&#43;"return new " &#43; tablename &#43; "DAL().Get(model)");sb.AppendLine(kongge2&#43;"}");sb.AppendLine(kongge1&#43;"}");sb.AppendLine("}");File.WriteAllText(textBox2.Text &#43; &#64;"\" &#43; tablename &#43; "BLL.cs", sb.ToString());}#endregionprivate void textBox1_TextChanged(object sender, EventArgs e){}/*点击按钮弹出“保存对话框”***************************************/private void btnRoutine_Click(object sender, EventArgs e){//SaveFileDialog saveFileDialog &#61; new SaveFileDialog();//if (saveFileDialog.ShowDialog() &#61;&#61; DialogResult.OK)//{// string localFilePath &#61; saveFileDialog.FileName.ToString();//获得文件路径 // textBox2.Text &#61; localFilePath;// saveFileDialog.RestoreDirectory &#61; true;//保存对话框是否记忆上次打开的目录 // // Directory.CreateDirectory(textBox2.Text);//}/*以上是保存对话框&#xff0c;下面是浏览对话框*/FolderBrowserDialog folderBrowserDialog1 &#61; new FolderBrowserDialog();//使用文件对话框查找文件夹创建的路径if (folderBrowserDialog1.ShowDialog() &#61;&#61; DialogResult.OK){string path &#61; folderBrowserDialog1.SelectedPath; //获取用户选中路径 textBox2.Text &#61; path; //显示路径/*▲Bug:路径不能手写。因为先点击按钮执行该函数&#xff0c;后面改变TextBox与该函数无关*/} }}
}

 

App.config

"1.0" encoding&#61;"utf-8" ?>
"v4.0" sku&#61;".NETFramework,Version&#61;v4.5" />"connstr" connectionString&#61;"Data Source&#61;.\;Initial Catalog&#61;CallCenter;Integrated Security&#61;True"/>

 

 

转:https://www.cnblogs.com/heyuchi-2013/p/3624217.html



推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 本文介绍了如何在MySQL中将零值替换为先前的非零值的方法,包括使用内联查询和更新查询。同时还提供了选择正确值的方法。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 展开全部下面的代码是创建一个立方体Thisexamplescreatesanddisplaysasimplebox.#Thefirstlineloadstheinit_disp ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • Windows7 64位系统安装PLSQL Developer的步骤和注意事项
    本文介绍了在Windows7 64位系统上安装PLSQL Developer的步骤和注意事项。首先下载并安装PLSQL Developer,注意不要安装在默认目录下。然后下载Windows 32位的oracle instant client,并解压到指定路径。最后,按照自己的喜好对解压后的文件进行命名和压缩。 ... [详细]
author-avatar
六道轮回2602906501
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有