0

我正在从文本文件中的 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());
       }
   }

我不知道在这种方法中要进行哪些更改

4

2 回答 2

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...
    }
}
于 2016-02-08T16:48:11.213 回答
0

您可以在您的选择语句中包含列名...。

Select Column1 from(select Sorter = 1, Convert(VARCHAR(max), Column1) as Column1
    from TableName union all
    select 0, 'Column1') X
order by Sorter, Column1
于 2016-02-08T17:08:56.093 回答