从SQL导出时,列名不保存在文本文件中

时间:2016-02-08 16:21:21

标签: c# sql .net export-to-text

我正在从文本文件中导出SQL表,数据导出正常,但列名不在文本文件中。 这是代码:

   public static void getfiles()
   {
       SqlDataReader reader;
       string query = "Select * from tTable";
       string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
       string strDelimiter = "\"|\"";
       string strFilePath = @"path";
       StringBuilder sb = new StringBuilder();

       using (SqlConnection conn = new SqlConnection(connStr))
       {
           conn.Open();
           using (reader = new SqlCommand(query, conn).ExecuteReader())
           {
               if (reader.HasRows)
               { 
                   Object[] items = new Object[reader.FieldCount];

                   while (reader.Read())
                   {
                       reader.GetValues(items);
                       foreach (var item in items)
                       {

                           sb.Append(item.ToString());
                           sb.Append(strDelimiter);
                       }
                       sb.Append("\n");
                   }
               }
           }
           conn.Close();
           File.WriteAllText(strFilePath, sb.ToString());
       }
   }

我不知道在这个方法中做了什么改变

2 个答案:

答案 0 :(得分:1)

您根本不写列名。这可以通过reader.GetName()方法实现,如下所示:

using (reader = new SqlCommand(query, conn).ExecuteReader())
{
    for (int i=0; i<reader.FieldCount; i++)
    {
        sb.Append(reader.GetName(i));
        sb.Append(strDelimiter);
    }
    sb.Append(Environment.NewLine);

    // your code here...
    if (reader.HasRows)
    {
        // etc...
    }
}

答案 1 :(得分:0)

您可以在select语句中包含列名....

Select Column1 from(select Sorter = 1, Convert(VARCHAR(max), Column1) as Column1
    from TableName union all
    select 0, 'Column1') X
order by Sorter, Column1