界面
代码
【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"/>