简体   繁体   English

使用sql数据读取器遍历sql表中的所有值

[英]loop through all values in sql table using sql data reader

I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is 我想获取与下面的查询相关的所有行,我的问题是只有一行不是所有的行,iam使用带有c#和ado.net的asp.net,我的代码逻辑是

if (!IsPostBack)
{
    string username = Session["username"].ToString();
    con.Open();
    string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
    SqlCommand cmd = new SqlCommand(strqryScript, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    SqlDataReader rdr = cmd.ExecuteReader();
    rdr.Read();         
    string name  = rdr["teach_id"].ToString();
    rdr.Close();

    string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
    SqlCommand cmd2 = new SqlCommand(query, con);
    SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
    SqlDataReader rdr2 = cmd2.ExecuteReader();
    while (rdr2.Read())
    {
        classname.Text = rdr2["class_id"].ToString();
    }
    con.Close();
}

extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. 额外注意我可以使用gridview绑定数据,但我想用许多表中的自定义信息填充我的表,所以我想使用html表并用我的自定义数据填充它。 any help please! 请帮忙! and thanks .. 并谢谢..

While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. 在第二个阅读器上循环时,可以在classname标签的Text属性上写入从阅读器中提取的值。 This will overwrite the previous text and leave you with the name of the last teacher retrieved. 这将覆盖以前的文本,并为您提供检索到的最后一位教师的姓名。 You need to add to the previous text or use a List. 您需要添加到以前的文本或使用列表。

classname.Text += rdr2["class_id"].ToString();

Said that, let me point you to a big problem in your code. 说,让我指出你的代码中的一个大问题。 String concatenation is really bad when you build sql commands. 构建sql命令时,字符串连接非常糟糕。 It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here 它为您提供了语法错误(如果您的输入文本包含单引号)或Sql Injection ,如此处所述

You should use parameterized queries like this (just for your first command) 您应该使用这样的参数化查询(仅适用于您的第一个命令)

string strqryScript = "select * from dbo.teachers where user_id = @id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("@id", username);
....

This is the issue you need to fix: 这是您需要解决的问题:

classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!

You need to make sure, you fill a list, a dataset or whatever, when reading the data! 在阅读数据时 ,您需要确保填写列表,数据集或其他内容!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM