foreach循环遍历数据库表.net c#

发布于 2024-09-30 01:00:21 字数 855 浏览 0 评论 0原文

这是漫长的一天,我似乎对当前的问题一片空白。下面是我的 HomeController 中包含的代码:

 public ActionResult About()
        {
            SqlDataReader rdr; 
            string fileName = "";
            const string connect = @"Server=localhost;Database=Images;user id=user; password=password;";

            using (var conn = new SqlConnection(connect))
            {

                var qry = "SELECT FileName FROM FileStore";
                var cmd = new SqlCommand(qry, conn);
                conn.Open();
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    rdr.Read();
                    fileName = rdr["FileName"].ToString();
                }

            }
            return View();
        }

我只想在视图中显示数据库中的文件名列表。我记得如何做到这一点,但我坚持如何编写将循环遍历我的 sql 表的循环语句。

有人可以指出我正确的方向吗?

It's been a long day and I seem to have drawn a blank with my current issue. Below is code contained in my HomeController:

 public ActionResult About()
        {
            SqlDataReader rdr; 
            string fileName = "";
            const string connect = @"Server=localhost;Database=Images;user id=user; password=password;";

            using (var conn = new SqlConnection(connect))
            {

                var qry = "SELECT FileName FROM FileStore";
                var cmd = new SqlCommand(qry, conn);
                conn.Open();
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    rdr.Read();
                    fileName = rdr["FileName"].ToString();
                }

            }
            return View();
        }

I simply want to display a list of the fileNames from the database in a view. I remember how to do this but I'm stuck on how to write the loop statement that will loop through my sql table.

Can someone point me in the right direction please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独﹏钓一江月 2024-10-07 01:00:21
if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
马蹄踏│碎落叶 2024-10-07 01:00:21

您的意思是像 while (rdr.Read()) 中那样吗?

while (rdr.Read()) 
{ 
    fileName = rdr["FileName"].ToString(); 
}

注意:使用此模式,您不需要 .HasRows

Do you mean as in while (rdr.Read())?

while (rdr.Read()) 
{ 
    fileName = rdr["FileName"].ToString(); 
}

NOTE: Using this pattern, you don't need .HasRows.

霞映澄塘 2024-10-07 01:00:21
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            Console.WriteLine("{0}",rdr.GetString(0));
        }
    }
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            Console.WriteLine("{0}",rdr.GetString(0));
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文