首页 > 解决方案 > 读取表格[列]并在控制台中显示

问题描述

我有一张表和大约 20 列,其中包含超过 5000 行。现在我想在控制台中显示所有 20 列,我来到第三列,我得到了错误

System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'

这是我的代码:

using System;
using System.Data.SqlClient;

namespace DbToJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            string constring = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True";
            string Query = "select * from AO_ASISTENCA";


            SqlConnection conDataBase = new SqlConnection(constring);
            SqlCommand cmd = new SqlCommand(Query, conDataBase);
            conDataBase.Open();
            using (SqlCommand command = new SqlCommand(Query, conDataBase))
            {

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                       Console.WriteLine("{0}", reader.GetString(0));
                       Console.WriteLine("{0}", reader.GetString(1));
                       Console.WriteLine("{1}", reader.GetString(0));


                    }
                }
            }

        }

    }
}

这种和平的代码让我出错

Console.WriteLine("{1}", reader.GetString(0));

当我将其更改为

Console.WriteLine("{0}", reader.GetString(2));

任何人都可以指导我并告诉我这有什么问题。也许我做错了什么,但我无法弄清楚这有什么问题。谢谢

标签: c#sql

解决方案


SQL部分没问题,但格式字符串错误:

Console.WriteLine("{1}", reader.GetString(0));

格式字符串中的{1}基本上是“第二个占位符”,但没有第一个。因此,当您将它reader.GetString(0)(或任何值)传递给第一个占位符时,就没有这样的占位符。

您在这里根本不需要格式字符串,因为您没有格式化任何内容。在每个输出行上,您可以只输出字符串值:

Console.WriteLine(reader.GetString(0));
Console.WriteLine(reader.GetString(1));
// etc.

通常,当您要将输出格式化为某种整体结构时,您会使用格式字符串。例如,您可以将输出行替换为以下内容:

Console.WriteLine("{0} - {1}", reader.GetString(0), reader.GetString(1));

这会将这两个值放入这两个字符串占位符中,创建单行输出,其中值由空格和连字符分隔。


推荐阅读