c# winform excel数据库模板转为SQL语句和获取sqlserver所有数据库和所有数据库表转换为c#类和生成增删查改基础sql语句

软件截图
excel生成数据库表
server数据库表字段转类
Main.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace excelToSql
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            openExcelToSql();
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {
            
        }

        public void openExcelToSql()
        {
            openExcelToSql f = new openExcelToSql();
            f.TopLevel = false;
            f.Visible = true;
            f.ControlBox = false;
            f.Dock = DockStyle.Fill;
            f.FormBorderStyle = FormBorderStyle.None;
            this.tabPage1.Controls.Add(f);
        }

        public void openSqlServerToType()
        {
            sqlServerToType fa = new sqlServerToType();
            fa.ControlBox = false;
            fa.Dock = DockStyle.Fill;
            fa.TopLevel = false;
            fa.Visible = true;
            fa.FormBorderStyle = FormBorderStyle.None;
            this.tabPage2.Controls.Add(fa);
        }

        private void tabPage2_Click(object sender, EventArgs e)
        {
            
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string formClass = tabPageOne.SelectedIndex.ToString();

            GenerateForm(formClass, sender);
        }

        public void GenerateForm(string form, object sender)
        {
            if (form == "0")
            {
                openExcelToSql();
            } else
            {
                openSqlServerToType();
            }
            
        }

    }
}

openExcelToSql.cs

using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using Dapper;
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.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Windows.Media.Animation;

namespace excelToSql
{
    public partial class openExcelToSql : Form
    {
        public static string filePath = Regex.Match(System.IO.Directory.GetCurrentDirectory(), @".*(?=:\\)").Value;
        public static string filePathExcel = filePath + ":\\Content\\Excel";
        public openExcelToSql()
        {
            InitializeComponent();
            label2.Text = filePathExcel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<tableList> tableList = new List<tableList>();
            string rows = "";
            try
            {
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string _filePath = openFileDialog1.FileName;
                    if (_filePath != "")
                    {
                        if (openFileDialog1.SafeFileName.Split('.')[1] != "xlsx")
                        {
                            textBox3.Text = "解析失败,解析0个数据库表,";
                            textBox2.Text = "文件格式不对,请导入.xlsx的文件";
                        } else {
                           using (FileStream fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
                        {
                            
                            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                            using (var package = new ExcelPackage(new FileInfo(_filePath)))
                            {
                                // step1 先读取excel
                                ExcelWorkbook excelWorkbook = package.Workbook;
                                foreach (var sheet in excelWorkbook.Worksheets)
                                {
                                    var colCount = sheet.Dimension.End.Column;
                                    var rowCount = sheet.Dimension.End.Row;
                                    rows += rowCount + ",";
                                    tableList tableHeader = new tableList();
                                    tableHeader.tableItem = new List<tableItem>();
                                    for (int r = sheet.Dimension.Start.Row; r <= rowCount; r++)
                                    {
                                        tableItem tableBody = new tableItem();
                                        for (int c = sheet.Dimension.Start.Column; c <= colCount; c++)
                                        {
                                            var value = sheet.Cells[r, c].Text.ToString().Trim();
                                            if (r==1 && c == 1)
                                            {
                                                tableHeader.tableName_Zh = value;
                                            }

                                            if (r == 1 && c == 2)
                                            {
                                                tableHeader.tableName_En = value;
                                            }

                                            if (r >= 3)
                                            {
                                                if(c == 1)
                                                {
                                                    tableBody.field = value;
                                                } else if (c == 2)
                                                {
                                                    tableBody.descs = value;
                                                }
                                                else if (c == 3)
                                                {
                                                    tableBody.dType = value;
                                                }
                                                else if (c == 4)
                                                {
                                                    tableBody.isNulls = value;
                                                }
                                                else if (c == 5)
                                                {
                                                    tableBody.isPrimarys = value;
                                                }
                                                else if (c == 6)
                                                {
                                                    tableBody.isIndexs = value;
                                                }
                                                else if(c== 7)
                                                {
                                                    tableBody.isDefault = value;
                                                    if(!string.IsNullOrEmpty(tableBody.field))
                                                    {
                                                        tableHeader.tableItem.Add(tableBody);
                                                    }
                                                    
                                                }
                                            }
                                        }
                                    }
                                    tableList.Add(tableHeader);
                                }

                                // step2 拼接创健表格T-sql
                                if (tableList.Count > 0)
                                {
                                    string tableNameAll = "";
                                    List<string> dataSql = new List<string>();
                                    for (int h = 0; h < tableList.Count; h++)
                                    {
                                        tableNameAll += tableList[h].tableName_En + "(" + tableList[h].tableName_Zh + "), ";
                                        string all = ""; // 这是最终拼接的结果
                                        string structures = "IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tableList[h].tableName_En + "]') AND type IN ('U'))" +
                                            " DROP TABLE [dbo].[" + tableList[h].tableName_En + "] " +
                                            "\r\nGO \r\n";
                                        string createTable = "CREATE TABLE [dbo].[" + tableList[h].tableName_En + "] (";
                                        string spaddextendedproperty = ""; // 这是拼接说明的
                                        string indexs = ""; // 这是拼接索引
                                        string primarys = ""; // 主键
                                        if (tableList[h].tableItem.Count > 0)
                                        {
                                            for (int k = 0; k < tableList[h].tableItem.Count; k++)
                                            {
                                                // 字段
                                                createTable += tableList[h].tableItem[k].field;
                                                // 类型
                                                createTable += " " + tableList[h].tableItem[k].dType;

                                                
                                                if (tableList[h].tableItem[k].isPrimarys + "" == "1")
                                                {
                                                    // 是否是主键
                                                    createTable += " IDENTITY(1,1) ";
                                                    primarys += "ALTER TABLE [dbo].[" + tableList[h].tableName_En + "] ADD CONSTRAINT [PK_" + tableList[h].tableName_En + "] PRIMARY KEY CLUSTERED ([" + tableList[h].tableItem[k].field + "]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] \r\nGO \r\n";
                                                }
                                                if (!string.IsNullOrEmpty(tableList[h].tableItem[k].isDefault))
                                                {
                                                    // 默认值
                                                    createTable += " DEFAULT " + tableList[h].tableItem[k].isDefault + " ";
                                                }
                                                if (tableList[h].tableItem[k].isNulls + "" == "1")
                                                {
                                                    // 是否为空
                                                    createTable += " NOT NULL,";
                                                }
                                                else
                                                {
                                                    // 是否为空
                                                    createTable += " NULL,";
                                                }

                                                // 说明
                                                if (!string.IsNullOrEmpty(tableList[h].tableItem[k].descs))
                                                {
                                                    spaddextendedproperty += "EXEC sp_addextendedproperty" +
                                                   " 'MS_Description', N'" + tableList[h].tableItem[k].descs + "'," +
                                                   " 'SCHEMA', N'dbo'," +
                                                   " 'TABLE', N'" + tableList[h].tableName_En + "'," +
                                                   " 'COLUMN', N'" + tableList[h].tableItem[k].field + "'" +
                                                   " \r\nGO \r\n";

                                                } else
                                                {
                                                    if (k == 0)
                                                    {
                                                        spaddextendedproperty += "EXEC sp_addextendedproperty" +
                                                    " 'MS_Description', N'" + tableList[h].tableName_Zh + "'," +
                                                    " 'SCHEMA', N'dbo'," +
                                                    " 'TABLE', N'" + tableList[h].tableName_En + "'," +
                                                    " 'COLUMN', N'" + tableList[h].tableItem[k].field + "'" +
                                                    " \r\nGO \r\n";
                                                    }
                                                    else
                                                    {
                                                        spaddextendedproperty += "EXEC sp_addextendedproperty" +
                                                    " 'MS_Description', N'" + tableList[h].tableItem[k].descs + "'," +
                                                    " 'SCHEMA', N'dbo'," +
                                                    " 'TABLE', N'" + tableList[h].tableName_En + "'," +
                                                    " 'COLUMN', N'" + tableList[h].tableItem[k].field + "'" +
                                                    " \r\nGO \r\n";
                                                    }
                                                }

                                                // 索引值
                                                if (tableList[h].tableItem[k].isIndexs + "" == "1")
                                                {
                                                    if(k==1)
                                                    {
                                                        indexs += "CREATE NONCLUSTERED INDEX [IX_" + tableList[h].tableName_En + "] ON [dbo].[" + tableList[h].tableName_En + "] ( [" + tableList[h].tableItem[k].field + "] ASC ) \r\nGO \r\n";
                                                    } else
                                                    {
                                                        indexs += "CREATE NONCLUSTERED INDEX [IX_" + tableList[h].tableName_En + "_" + (k-1) + "] ON [dbo].[" + tableList[h].tableName_En + "] ( [" + tableList[h].tableItem[k].field + "] ASC ) \r\nGO \r\n";
                                                    }
                                                    
                                                }
                                            }
                                        }

                                        createTable += " ) \r\nGo \r\n ALTER TABLE [dbo].[" + tableList[h].tableName_En + "] SET (LOCK_ESCALATION = TABLE) \r\nGO \r\n";
                                        spaddextendedproperty += " DBCC CHECKIDENT ('[dbo].[" + tableList[h].tableName_En + "]', RESEED, 13) \r\nGO \r\n";
                                        all = structures + createTable + spaddextendedproperty + indexs + primarys;
                                        dataSql.Add(all);

                                    }
                                    textBox3.Text = "解析成功,解析" + dataSql.Count + "个数据库表,分别是" + tableNameAll +"解析行数:" + rows;
                                    textBox2.Text = string.Join("\r\n", dataSql);
                                    //string constr = "data source =.;initial catalog = " + textBox1.Text.Trim() + ";integrated security = true;";
                                    //using (IDbConnection connection = new SqlConnection(constr))
                                    //{
                                    //    connection.Open();
                                    //    if (connection.State != ConnectionState.Open)
                                    //        connection.Open();

                                    //    IDbTransaction transaction = connection.BeginTransaction();
                                    //    try
                                    //    {

                                    //        for (int a = 0; a < dataSql.Count; a++)
                                    //        {
                                    //            connection.Execute(dataSql[a], null, transaction);
                                    //        }
                                    //        textBox3.Text = "导入成功,导入" + dataSql.Count + "个数据库表,分别是" + tableNameAll;
                                    //        transaction.Commit();
                                    //        textBox2.Text = string.Join("\r\n", dataSql);
                                    //    }
                                    //    catch (Exception ex)
                                    //    {
                                    //        transaction.Rollback();
                                    //        textBox3.Text = "导入失败,导入0个数据库表,";

                                    //        textBox2.Text = ex.ToString() + "\r\n导入:" + string.Join("\r\n", dataSql);
                                    //    }

                                    //}
                                }
                                else
                                {
                                    textBox3.Text = "解析失败,解析0个数据库表,";
                                    
                                    textBox2.Text = "暂无";
                                }
                            }
                        }
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {
                textBox3.Text = "解析失败,解析0个数据库表,";
                textBox2.Text = ex.ToString();
            }
        }

        /// <summary>
        /// 导出数据库模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string strFile = filePathExcel + "\\创健数据库模板.xlsx";
            if (!Directory.Exists(filePathExcel))
            {
                Directory.CreateDirectory(filePathExcel);
            }
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet xlSheet = package.Workbook.Worksheets.Add("创建表");
                
               
                xlSheet.Cells[1, 1].Value = "表中文名称(中文,示例:部门明细表)";
                xlSheet.Cells[1, 2].Value = "表英文名称(英文,示例:DepartDetails)";
                xlSheet.Cells[1, 1].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[1, 2].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[1, 2, 1, 6].Merge = true;
                xlSheet.Row(2).Style.Font.Name = "Microsoft YaHei";
                xlSheet.Row(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                xlSheet.Row(2).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                

                xlSheet.Cells[2, 1].Value = "字段";
                xlSheet.Cells[2, 2].Value = "说明";
                xlSheet.Cells[2, 3].Value = "类型(nvarchar(100))";
                xlSheet.Cells[2, 4].Value = "是否为空(默认不填写就是为空,1为不为空,2为可以空)";
                xlSheet.Cells[2, 5].Value = "主键(1.为唯一标识主键,2.不为主键,不填默认不是主键)";
                xlSheet.Cells[2, 6].Value = "索引(1.为索引,2.不为索引,不填默认不是索引)";
                xlSheet.Cells[2, 7].Value = "默认值";
                xlSheet.Column(1).Width = 20;//设置列宽
                xlSheet.Column(2).Width = 20;//设置列宽
                xlSheet.Column(3).Width = 30;//设置列宽
                xlSheet.Column(4).Width = 30;//设置列宽
                xlSheet.Column(5).Width = 30;//设置列宽
                xlSheet.Column(6).Width = 30;//设置列宽
                xlSheet.Column(7).Width = 30;//设置列宽
                xlSheet.Row(2).Style.Font.Name = "Microsoft YaHei";
                xlSheet.Row(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                xlSheet.Row(2).Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                
                
                xlSheet.Row(1).Height = 40;//自动调整行高
                xlSheet.Row(2).Height = 40;//自动调整行高
                xlSheet.Cells[2, 3].Style.Font.Size = 10;
                xlSheet.Cells[2, 3].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[2, 4].Style.Font.Size = 10;
                xlSheet.Cells[2, 4].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[2, 5].Style.Font.Size = 10;
                xlSheet.Cells[2, 5].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[2, 6].Style.Font.Size = 10;
                xlSheet.Cells[2, 6].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells[2, 7].Style.Font.Size = 10;
                xlSheet.Cells[2, 7].Style.WrapText = true;//自动换行,全局
                xlSheet.Cells.Style.Font.Name = "Microsoft YaHei";//全局

                if (Directory.Exists(filePathExcel))
                {
                    DelectDir(filePathExcel);//导出excel前先清楚文件夹中文件,防止数据量大
                }

                package.SaveAs(new FileInfo(strFile));
                package.Dispose();
                label2.Text = strFile;
            }
        }

        
        /// <summary>
        /// 删除指定文件夹中文件
        /// </summary>
        /// <param name="srcPath"></param>
        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}

sqlServerToType.cs

using OfficeOpenXml.Style;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace excelToSql
{
    public partial class sqlServerToType : Form
    {
        public static string connectStr = "Data Source=./;Initial Catalog=master;integrated security = true;";
        public sqlServerToType()
        {
            InitializeComponent();
        }

        private void sqlServerToType_Load(object sender, EventArgs e)
        {
            this.comboBox1.DisplayMember = "pName";
            this.comboBox1.ValueMember = "pName";
            this.comboBox1.DataSource = GetAllDataBase();
        }

        /// <summary>
        /// 取所有数据库名,添加到lvDB
        /// </summary>
        /// <returns></returns>
        private ArrayList GetAllDataBase()
        {
            ArrayList DBNameList = new ArrayList();
            SqlConnection Connection = new SqlConnection(String.Format(connectStr));
            DataTable DBNameTable = new DataTable();
            SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", Connection);
            lock (Adapter)
            {
                Adapter.Fill(DBNameTable);
            }
            int s = 1;
            foreach (DataRow row in DBNameTable.Rows)
            {
                DBNameList.Add(new SetCls(s.ToString(), row["name"].ToString()) );
                s++;
            }
            return DBNameList;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedValue != null)
            {
                this.comboBox2.DisplayMember = "pName";
                this.comboBox2.ValueMember = "pName";
                this.comboBox2.DataSource = GetTablesName();
            }
            
        }

        /// <summary>
        /// 获取所有数据库表
        /// </summary>
        private ArrayList GetTablesName()
        {
            ArrayList DBNameList = new ArrayList();
            using (SqlConnection sqlConn = new SqlConnection("Data Source=./;Initial Catalog=" + this.comboBox1.SelectedValue + ";integrated security = true;"))
            {
                sqlConn.Open();
                DataTable dt = sqlConn.GetSchema("Tables");
                DataTable sortTable = dt.Clone();

                DataView dv = dt.DefaultView;
                dv.Sort = "TABLE_NAME asc"; // 排序
                sortTable = dv.ToTable();
                int s = 1;
                foreach (DataRow dr in sortTable.Rows)
                {
                    DBNameList.Add(new SetCls(s.ToString(), (String)dr["TABLE_NAME"]));
                    s++;
                }

                sqlConn.Close();
                return DBNameList;
            }
        }

        private string GetTableFields()
        {
            string fileds = "";
            using (SqlConnection sqlConn = new SqlConnection("Data Source=./;Initial Catalog=" + this.comboBox1.SelectedValue + ";integrated security = true;"))
            {
                sqlConn.Open();
                try
                {
                    string[] restrictionValues = new string[4];
                    restrictionValues[0] = null; // Catalog
                    restrictionValues[1] = null; // Owner
                    restrictionValues[2] = this.comboBox2.SelectedValue.ToString(); // Table
                    restrictionValues[3] = null; // Column

                    using (DataTable dt = sqlConn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues))
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            Field field;
                            field.Name = dr["column_name"].ToString();
                            field.Type = dr["data_type"].ToString();
                            if(field.Type == "bit")
                            {
                                field.Type = "bool";
                            } else if (field.Type.IndexOf("datetime")>-1)
                            {
                                field.Type = "string";
                            }
                            else if (field.Type=="nchar" || field.Type == "char" || field.Type == "nvarchar" || field.Type == "varchar" || field.Type == "text")
                            {
                                field.Type = "string";
                            }
                            fileds += "public " + field.Type + " " + field.Name + " {get;set;} \r\n";
                        }
                    }
                }
                catch (Exception ex)
                {
                    fileds = ex.ToString();
                }
                finally
                {
                    sqlConn.Dispose();
                }
            }
            return fileds;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(this.comboBox2.SelectedItem!=null)
            {
              this.textBox1.Text = GetTableFields();
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.comboBox2.SelectedItem != null)
            {
                this.textBox1.Text = GetAddChangeAddSql();
            }
        }
        
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.comboBox2.SelectedItem != null)
            {
                this.textBox1.Text = GetAddChangeDeleteSql();
            }
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.comboBox2.SelectedItem != null)
            {
                this.textBox1.Text = GetAddChangeSql();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (this.comboBox2.SelectedItem != null)
            {
                this.textBox1.Text = GetListSql();
            }
        }

        /// <summary>
        /// 增
        /// </summary>
        /// <returns></returns>
        private string GetAddChangeAddSql()
        {
            string add = " insert into [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] (";
            string result = "";
            List<string> tableDt = new List<string>();
            using (SqlConnection sqlConn = new SqlConnection("Data Source=./;Initial Catalog=" + this.comboBox1.SelectedValue + ";integrated security = true;"))
            {
                sqlConn.Open();
                try
                {
                    string[] restrictionValues = new string[4];
                    restrictionValues[0] = null; // Catalog
                    restrictionValues[1] = null; // Owner
                    restrictionValues[2] = this.comboBox2.SelectedValue.ToString(); // Table
                    restrictionValues[3] = null; // Column

                    using (DataTable dt = sqlConn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues))
                    {
                        int s = 1;
                        DataTable sortTable = dt.Clone();

                        DataView dv = dt.DefaultView;
                        dv.Sort = "column_name asc"; // 排序
                        sortTable = dv.ToTable();
                        foreach (DataRow dr in sortTable.Rows)
                        {

                            tableDt.Add(dr["column_name"].ToString());
                            s++;
                        }
                        add += string.Join(",", tableDt) + ") values ( @" + string.Join(",@", tableDt) + ")";

                    }
                    result = '"' + add + '"' + ";";
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                }
                finally
                {
                    sqlConn.Dispose();
                }
            }
            return result;
        }

        
        /// <summary>
        /// 增删改查
        /// </summary>
        /// <returns></returns>
        private string GetAddChangeDeleteSqls()
        {
            string add = " insert into [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] (";
            string editor = " update [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] set ";
            string delete = " delete from [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] where Id = @[" + this.comboBox2.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] where Id = @Id ";
            string result = "";
            List<string> tableDt = new List<string>();
            using (SqlConnection sqlConn = new SqlConnection("Data Source=./;Initial Catalog=" + this.comboBox1.SelectedValue + ";integrated security = true;"))
            {
                sqlConn.Open();
                try
                {
                    string[] restrictionValues = new string[4];
                    restrictionValues[0] = null; // Catalog
                    restrictionValues[1] = null; // Owner
                    restrictionValues[2] = this.comboBox2.SelectedValue.ToString(); // Table
                    restrictionValues[3] = null; // Column

                    using (DataTable dt = sqlConn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues))
                    {
                        int s = 1;
                        DataTable sortTable = dt.Clone();

                        DataView dv = dt.DefaultView;
                        dv.Sort = "column_name asc"; // 排序
                        sortTable = dv.ToTable();
                        foreach (DataRow dr in sortTable.Rows)
                        {

                            tableDt.Add(dr["column_name"].ToString());
                            if (s == dt.Rows.Count)
                            {
                                editor += dr["column_name"].ToString() + "=@" + dr["column_name"].ToString();
                            }
                            else
                            {
                                editor += dr["column_name"].ToString() + "=@" + dr["column_name"].ToString() + ",";
                            }
                            s++;
                        }
                        add += string.Join(",", tableDt) + ") values ( @" + string.Join(",@", tableDt) + ")";

                    }
                    result = '"' + add + '"' + ";" + "\r\n" + '"' + editor + '"' + ";" + "\r\n" + '"' + delete + '"' + ";";
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                }
                finally
                {
                    sqlConn.Dispose();
                }
            }
            return result;
        }

        /// <summary>
        /// 删
        /// </summary>
        /// <returns></returns>
        private string GetAddChangeDeleteSql()
        {
            string delete = " delete from [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] where Id = @Id ";
            string result = "";
            result = '"' + delete + '"' + ";";
            return result;
        }

        /// <summary>
        /// 改
        /// </summary>
        /// <returns></returns>
        private string GetAddChangeSql()
        {
            
            string editor = " update [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] set ";
            string result = "";
            List<string> tableDt = new List<string>();
            using (SqlConnection sqlConn = new SqlConnection("Data Source=./;Initial Catalog=" + this.comboBox1.SelectedValue + ";integrated security = true;"))
            {
                sqlConn.Open();
                try
                {
                    string[] restrictionValues = new string[4];
                    restrictionValues[0] = null; // Catalog
                    restrictionValues[1] = null; // Owner
                    restrictionValues[2] = this.comboBox2.SelectedValue.ToString(); // Table
                    restrictionValues[3] = null; // Column

                    using (DataTable dt = sqlConn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues))
                    {
                        int s = 1;
                        DataTable sortTable = dt.Clone();

                        DataView dv = dt.DefaultView;
                        dv.Sort = "column_name asc"; // 排序
                        sortTable = dv.ToTable();
                        foreach (DataRow dr in sortTable.Rows)
                        {

                            tableDt.Add(dr["column_name"].ToString());
                            if (s == dt.Rows.Count)
                            {
                                editor += dr["column_name"].ToString() + "=@" + dr["column_name"].ToString();
                            }
                            else
                            {
                                editor += dr["column_name"].ToString() + "=@" + dr["column_name"].ToString() + ",";
                            }
                            s++;
                        }
                        

                    }
                    result =  '"' + editor + '"' + ";" ;
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                }
                finally
                {
                    sqlConn.Dispose();
                }
            }
            return result;
        }

        /// <summary>
        /// 查
        /// </summary>
        /// <returns></returns>
        private string GetListSql()
        {
            string a1 = '"' + "select * from [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] where 1 = 1 order by Update_Time desc offset + ((info.currentPage - 1) * info.pageSize) +  rows fetch next + info.pageSize + rows only" + '"' + ";";
            string a2 = '"' + "select count(*) as Total from [" + this.comboBox1.SelectedValue + "].[dbo].[" + this.comboBox2.SelectedValue + "] where 1 = 1 " + '"' + ";";
            return a1 + "\r\n" + a2;
        }



    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙滩上的一颗石头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值