首页 > 解决方案 > SqlDataReader,缺少列

问题描述

我有以下创建语句:

CREATE TABLE Products
(
      SKU char(255) NOT NULL PRIMARY KEY
    , Supplier int FOREIGN KEY REFERENCES Suppliers(Id) NOT NULL 
    , Category char(255) FOREIGN KEY REFERENCES ProductsCategories(name) 
    , Temp char(255) FOREIGN KEY REFERENCES StorageTemperatures(name)
    , Description char(255) NOT NULL UNIQUE 
    , Price money NOT NULL
);

我有以下 C# 程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace mssqlDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");

            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = "Data Source=localhost;Initial Catalog=my_playground;Integrated Security=True";

                connection.Open();
                Console.WriteLine("Successfully connected to database! I'M NOT DUMB");

                SqlCommand command = new SqlCommand("SELECT * FROM Products", connection);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // while there is another record present
                    while (reader.Read())
                    {
                        Console.WriteLine(string.Format("There are {0} columns", reader.FieldCount));    
                        Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3} \t", reader[0], reader[1], reader[2], reader[3]));
                    }
                }

                connection.Close();
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
    }
}

如果我尝试访问超过 3 列,则会引发错误:

System.IndexOutOfRangeException

为什么会这样做,我该如何解决?

请注意, 的值为reader.FieldCount3。

标签: c#sql-server

解决方案


推荐阅读