在 C# 代码隐藏中使用值创建 table 脚本

Creating table script with values in codebehind inC#

我想用 ado.net 构建一个控制台应用程序,我从数据库中获取 table 并将其转换为文件中的字符串输出。我想用 stringbuilder 来做这个。但在我获取数据并将其写入字符串生成器之前,我想用“xxx”填充 table Person“name”和“last name”的 2 个字段。最终结果必须是一个在 tsql 中包含创建和插入值语句的文件。

class Program
    {
        static void Main(string[] args)
        {
            string ConString = @"Data Source=.;Initial Catalog=TEST;Integrated Security=True";

           

            SqlConnection con = new SqlConnection(ConString);
            string querystring = "Select * from person";

           

            con.Open();
            SqlCommand cmd = new SqlCommand(querystring, con);
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString() + " " + reader[2].ToString() + reader[3].ToString());
            }

            StringBuilder builder = new StringBuilder();
            builder.Append("");
            //CREATE TABLE Person
            //[name] [varchar](20) NOT NULL,
            //[surname] [varchar](20) NOT NULL,        
            //[Gender] [varchar](5) NOT NULL


            //INSERT VALUES (...,...) with modifyed name and surname data and put it in the stringbuilder


            string innerString = builder.ToString();

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\script.txt"))
            {
                file.WriteLine(innerString.ToString());
            }

         
               
            Console.Read();
        }

       
    }

有什么聪明的方法可以做到这一点吗? 谢谢

我相信这就是您所追求的:

static void Main(string[] args)
    {
        string ConString = @"Data Source=.;Initial Catalog=Clients;Integrated Security=True";

        SqlConnection con = new SqlConnection(ConString);
        string querystring = "Select * from person";

        con.Open();
        SqlCommand cmd = new SqlCommand(querystring, con);
        SqlDataReader reader = cmd.ExecuteReader();
        StringBuilder builder = new StringBuilder();

        builder.AppendLine("CREATE TABLE PERSON");
        builder.AppendLine("(");
        builder.AppendLine("[name] [varchar](20) NOT NULL,");
        builder.AppendLine("[surname] [varchar](20) NOT NULL,");
        builder.AppendLine("[gender] [varchar](5) NOT NULL");
        builder.AppendLine(")");

        while (reader.Read())
        {
            var name = reader[0].ToString();
            var surname = reader[1].ToString();
            var gender = reader[2].ToString();
            var value4 = reader[3].ToString();

            Console.WriteLine(name + " " + surname + " " + gender + value4);

            builder.AppendLine("INSERT INTO PERSON (name, surname, gender) VALUES ('" + name + "','" + surname + "','" + gender + "')");
        }

        System.IO.File.WriteAllText(@"\script.txt", builder.ToString());

        Console.Read();
    }