简体   繁体   English

SQL数据检索-C#

[英]SQL data retrieve - C#

how do i retrieve data from a table within a loop or something. 我如何从循环或其他内容中的表中检索数据。 That means I want to retrieve row by row at a time. 这意味着我想一次一行一行地检索。 but the sequence of rows may differ. 但是行的顺序可能不同。 For example, 1st time i want 5rd row,then 2nd, then 9...so on. 例如,第一次我想要第5行,然后第2行,然后9 ...等等。

I searched it through the internet. 我通过互联网搜索了它。 I got only two answers. 我只有两个答案。

  1. Use several SqlConnection objects. 使用几个SqlConnection对象。

  2. reader= sqlCommand.ExecuteReader(); reader = sqlCommand.ExecuteReader(); While(reader.Read()){ reader["Column Name"].ToString(); While(reader.Read()){reader [“ Column Name”]。ToString(); } }

If you got my problem, please help me Thank you. 如果您遇到我的问题,请帮助我,谢谢。

Sounds like you should correct your data layer to return the values in the order you are going to process them . 听起来您应该更正数据层以按照处理顺序返回值 It would be easiest and fastest! 这将是最简单,最快的! :) :)

As an alternative I'd suggest that you load your result into a DataTable: 另外,我建议您将结果加载到DataTable中:

    DataTable table = new DataTable();
    using ( SqlCommand command = new SqlCommand() )
    {
           // TODO: Set up your command here
        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
        {
            adapter.Fill(table);
        }
    }

    // Use your DataTable like this...

    if ( table.Rows.Count >= 5 ) {
        DataRow firstRow = table.Rows[0]; // #1 row
        DataRow fifthRow = table.Rows[4]; // #5 row
        DataRow secondRow = table.Rows[1]; // #2 row
    }

/Alex /亚历克斯

It's probably best to read your data into a DataSet, as shown in this example: 如以下示例所示,最好将数据读入数据集:

http://quickstart.developerfusion.co.uk/quickstart/howto/doc/adoplus/GetDataFromDB.aspx http://quickstart.developerfusion.co.uk/quickstart/howto/doc/adoplus/GetDataFromDB.aspx

The reader approach is usually the way to go, but your query (or SP) must already select the data in the order you want to retrieve it. 阅读器方法通常是可以采用的方法,但是您的查询(或SP)必须已经按照要检索的顺序选择了数据。

Alternatively you can load everything into a DataSet and do random access on the rows in it. 或者,您可以将所有内容加载到DataSet中并对其中的行进行随机访问。

Two ways, that I see: 我看到两种方式:

1) Get all rows in one sql statement, then access the row you need in memory. 1)在一条sql语句中获取所有行,然后访问内存中所需的行。

Or (of "everything" is too much or you need recent data) 或(“一切”太多,或者您需要最新数据)

2) Get only the specific row you need, and again for the next row. 2)仅获取所需的特定行,然后为下一行再次获取。

What exactly are you trying to achieve? 您到底想达到什么目的? Retrieve random rows from a DS or do you have certain criteria for selecting which rows you want returned? 从DS检索随机行,或者您是否有某些标准来选择要返回的行? And if so couldn't you order them before loading them into the reader? 如果可以的话,在将它们加载到阅读器之前是否可以订购它们?

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

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