c# - 读取表格[列]并在控制台中显示
问题描述
我有一张表和大约 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));
任何人都可以指导我并告诉我这有什么问题。也许我做错了什么,但我无法弄清楚这有什么问题。谢谢
解决方案
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));
这会将这两个值放入这两个字符串占位符中,创建单行输出,其中值由空格和连字符分隔。
推荐阅读
- mysql - MAMP Pro MySQL 8 无法启动
- sparql - SPARQL 在查询中,找到特定类后如何过滤掉超类?
- c# - 包括花费很长时间来执行
- ruby - rvm:创建文件 bin-ruby-2.6.3.tar.bz2.part 失败:权限被拒绝
- shopify - 这是在 Shopify 模板文件中留下注释的正确方法吗?
- google-cloud-platform - 谷歌云站点返回“指定的密钥不存在。”
- pandas - 我正在尝试使用 pandas 多索引对散景图上的条形图进行分类,但我似乎无法让它工作
- visual-studio-code - vscode中是否有从面包屑中过滤变量的设置?
- typescript - 如何删除一些用于将数据发送到 graphql 的属性
- javascript - 为什么我要检索的 URL 参数没有完全显示?