【发布时间】:2011-03-18 13:35:47
【问题描述】:
我有一个用户表 (tblUsers),其中包含大学工作人员的详细信息。我正在尝试使用与所选模块关联的讲师姓名填充文本框。
我正在获取与特定模块关联的所有用户 ID,测试用户是否是讲师,如果是,那么我将 ID 添加到 ArrayList。
然后我遍历这个数组并在每次遍历当前 ID 的过程中调用下面的方法。
但是,如果您查看下面的方法,我正在使用 SqlDataReader 并且在从该行读取时遇到错误:
txtLecturerName.Text += myReader["First_Name"].ToString();
错误信息是: 'myReader["First_Name"]' 引发了类型为 'System.IndexOutOfRangeException' 的异常
我使用的表格布局在方法代码下方。对此的任何帮助将不胜感激,我只需一杯咖啡就可以将头穿过屏幕。
public void outputLecturerNames(string lecturerID)
{
// Create a new Connection object using the connection string
SqlConnection myConnection = new SqlConnection(conStr);
// If the connection is already open - close it
if (myConnection.State == ConnectionState.Open)
{
myConnection.Close();
}
// 'using' block allows the database connection to be closed
// first and then the exception handling code is triggered.
// This is a better approach than using a 'finally' block which
// would close the connection after the exception has been handled.
using (myConnection)
{
try
{
// Open connection to DB
myConnection.Open();
SqlCommand selectCommand = new SqlCommand(selectQuery, myConnection);
// Declare a new DataReader
SqlDataReader myReader;
selectQuery = "SELECT * FROM tblUsers WHERE User_ID='";
selectQuery += lecturerID + "'";
myReader = selectCommand.ExecuteReader();
while (myReader.Read())
{
txtLecturerName.Text += myReader["First_Name"].ToString();
txtLecturerName.Text += " ";
txtLecturerName.Text += myReader["Last_Name"].ToString();
txtLecturerName.Text += " , ";
}
myReader.Close();
}
catch (Exception err)
{
Console.WriteLine("Error: " + err);
}
}
}
tbl 用户:
[User_ID][First_Name][Last_Name][Email_Address]
【问题讨论】:
-
tblUsers的结构是什么?错误说没有名为:First_Name 的列。
-
您好 Fosco,列名在方法代码下方以正确的顺序列出。谢谢
-
附注 - 连接用户输入字符串时要非常小心,或者更好地参数化查询或使用 ORM 工具。
-
如果从 SQL 语句中删除 where 子句会发生什么?我想知道讲师 ID 中的某些内容是否导致 SQL 语句被修改(SQL 注入类型的东西)。另外,如果您使用 0 的索引会发生什么?在您对 devio 的回复中,您说您尝试使用 1 的索引。
-
谢谢大家!你们都很棒!如果您查看该方法,您会发现我在分配 selectQuery 之前愚蠢地声明了我的 SqlCommand,这意味着我在查询中使用了错误的 select 语句 - 因此 IndexOutOfRange 异常。再次感谢。
标签: c# sql database arraylist sqldatareader