c# - 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.FieldCount
3。
解决方案
推荐阅读
- c# - 在C#中自动添加多个文本框而没有按钮
- python - 无法通过 pip 或 npm 安装软件包
- javascript - 有没有办法将 JavaScript 函数调用答案传递给要在同一页面中使用的 PHP 变量?
- python-3.x - 在破折号的条形图中删除高度为 0 的条形
- api - Qliksense REST 连接器错误:BAD_AUTH_CODE
- angular - node_modules/xterm/typings/xterm.d.ts(10,1) 中的错误:错误 TS1084:无效的“参考”指令语法
- sql - sql server 选择组的第一行
- angular - 如何从浏览器访问网络选项卡中的请求标头部分
- ansible - 有没有办法将完整的 Ansible 剧本(而不仅仅是任务)委托给另一个主机?
- javascript - 通过对象属性实现条件逻辑