简体   繁体   中英

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

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. 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. 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. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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