C# 读取表[列]并在控制台中显示
我有一个表和大约20列,其中包含5000多行。 现在我想在控制台中显示所有的20列,我来到第三列,我得到了一个错误C# 读取表[列]并在控制台中显示,c#,sql,C#,Sql,我有一个表和大约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 D
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));
这会将这两个值放入这两个字符串占位符中,创建一行输出,其中的值由空格和连字符分隔。错误是不言自明的:
“{1}”是错误的,因为您没有将第三个参数传递到控制台。WriteLine
@谢谢,我解决了以下问题:)System.InvalidCastException:“无法将类型为'System.DateTime'的对象强制转换为类型为'System.String'。看起来我的一列中有一列包含datatimefield@Xerror:听起来您可能试图对非字符串的数据库值调用.GetString()
。查看数据读取器上可用的其他.Get…()
方法:。您甚至可以使用.GetValue()
,它返回一个对象,您可以尝试在代码中转换为所需的格式。我们还强烈建议您研究更现代的数据访问技术,例如Entity Framework,它倾向于更干净地处理数据类型
@Xerror:对,这就是为什么您希望在数据读取器上使用不同的方法来获取不同的数据类型。