我有一张包含大学工作人员详细信息的用户(tblUsers)表。我正在尝试使用与选定模块关联的讲师姓名填充文本框。SQL使用数据读取器从数据库问题读取
我正在获取与特定模块关联的所有UserID,测试用户是否是演讲者,如果是这样,那么我将该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);
}
}
}
向tblUsers:
[User_ID][First_Name][Last_Name][Email_Address]
tblUsers的结构是什么?该错误表示没有名为First_Name的列。 – Fosco 2010-07-20 16:53:29
Hi Fosco,列名称按照方法代码下方的正确顺序列出。谢谢 – Frank 2010-07-20 17:15:04
在旁注 - 要非常小心地连接用户输入字符串或更好地参数化查询或使用ORM工具。 – 2010-07-20 17:23:42