我有一张表和大约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));
任何人都可以引导我并告诉我这有什么问题。也许我做错了什么,但是我无法弄清楚这是怎么回事。 谢谢
答案 0 :(得分:1)
SQL部分很好,但是格式字符串错误:
Console.WriteLine("{1}", reader.GetString(0));
格式字符串中的{1}
基本上是“第二个占位符”,但没有第一个。因此,当您将其传递给reader.GetString(0)
(或任何值)以放入 first 占位符时,就没有此类占位符。
由于您没有格式化任何内容,因此您实际上根本不需要格式化字符串。在每条输出行上,您只需输出字符串值:
Console.WriteLine(reader.GetString(0));
Console.WriteLine(reader.GetString(1));
// etc.
通常,当您要将输出格式化为某种整体结构时,会使用格式字符串。例如,您可以使用以下内容替换输出行:
Console.WriteLine("{0} - {1}", reader.GetString(0), reader.GetString(1));
这会将这两个值放入这两个字符串占位符中,从而创建一行输出,其中值之间用空格和连字符分隔。