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

时间:2019-03-15 10:05:26

标签: c# sql sql-server save qsqlquery

我写了一种将特定表的内容保存到文本文件的方法。不幸的是,没有检索到列名。每个单元的“仅”数据将写入文本文件。

我如何调整我的代码以使其还包括列名?

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();
      }     
   }
}

3 个答案:

答案 0 :(得分: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++;         
    }
}

答案 1 :(得分:0)

嗨,我想您可以使用reader.GetName('index')作为第一列:reader.GetName(0)

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

答案 2 :(得分:0)

请尝试此操作,然后根据需要设置数据行和列的名称。

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();
      }     
   }