将 SQL 查询保存到文本文件时如何检索列名

How to retrieve column names when saving a SQL query to a text file

我写了一个方法,可以将特定 table 的内容保存到文本文件中。不幸的是,没有检索到列的名称。 "Only"将每个单元格的数据写入文本文件。

我需要如何调整我的代码以包含列的名称?

private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile, string nameOfRow0, string nameOfRow1, string nameOfRow2)
{
  StreamWriter outputFile = new StreamWriter(dWTestResult + "\DatabaseUpgradeCheck\" + nameOfOutputFile);

  using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
  {
      SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
      sqlCon.Open();
      SqlDataReader reader = command.ExecuteReader();
      try
      {
          while (reader.Read())
          {
              outputFile.WriteLine(String.Format("{0}, {1}, {2}",
              reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));
          }
      }
      catch (Exception ex)
      {
          logger.Debug(ex, "Writing Database Output to the text file failed");
      }
      finally
      {
          reader.Close();
          outputFile.Close();
      }     
   }
}

您好,我认为您可以使用:reader.GetName('index') 例如第一列:reader.GetName(0)

查看更多信息 link:https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.getname?view=netframework-4.7.2

添加一个 count 变量,如果 count == 0 添加列名称。看起来您已经知道列的名称,因此您有几个选项。

第一个选项:只写名字。

try
{
    int count = 0;
    while (reader.Read())
    {
        if (count == 0)
        {
            outputFile.WriteLine(String.Format("{0}, {1}, {2}",
                nameOfRow0, nameOfRow1, nameOfRow2));
        }

        outputFile.WriteLine(String.Format("{0}, {1}, {2}",
            reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));

        count++;    
    }
}

或者(如果您不知道列名)使用 reader.GetName(i):

try
{
    int count = 0;
    while (reader.Read())
    {
        // if this is the first row, read the column names
        if (count == 0)
        {
            outputFile.WriteLine(String.Format("{0}, {1}, {2}",
               reader.GetName(0), reader.GetName(1), reader.GetName(2)));
        }

        // otherwise just the data (including 1st row)
        outputFile.WriteLine(String.Format("{0}, {1}, {2}",
           reader.GetValue(0), reader.GetValue(1), reader.GetValue(2)));

        count++;         
    }
}

请试试这个并根据需要设置数据行和列名称。

using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
  {
      SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
      sqlCon.Open();
      SqlDataAdapter da = new SqlDataAdapter();
      da.SelectCommand = cmd; 
      DataTable dt = new DataTable(); 
      da.fill(dt);
      try
      {
         if(dt != null && dt.Rows.Count > 0)
         {
            string columnName = dt.Columns[0].ToString();
            DataRow dr = dt.Rows[0];
         }
      }
      catch (Exception ex)
      {
          logger.Debug(ex, "Writing Database Output to the text file failed");
      }
      finally
      {
          reader.Close();
          outputFile.Close();
      }     
   }