如何计算 MySqlDataReader 中的行数?

发布于 2024-08-11 03:57:42 字数 281 浏览 5 评论 0原文

我已成功将项目从 odbc.datareader 切换到 mysql.datareader。问题是,对于第一个 /odbc datareader),AffectedRows 属性即使是纯查询也能正确检索行数。但它不适用于 mysql.datareader,那么它是-1。 所以我看不到如何检索行数,即“结果视图”。 编辑:我知道它的仅向前阅读器,但我不明白如下:如果在 DBreader=command.ExecuteRader() 行上放置断点,我可以看到 DBreader - 在结果视图中 - 与行一样多的对象应该是。怎么跑完就知道了? 谢谢

I have successfully switched my project from odbc.datareader to mysql.datareader. The problem is that with the first one /odbc datareader), the AffectedRows property retrieves the number of rows correctly even when it was pure query. But it doesn work with mysql.datareader, its -1 then.
So I cannot see the way how to retrieve the number of rows, i.e. "result views".
EDIT: I know its forward only reader, but what I dont understand is following: If a place a breakpoint to the line DBreader=command.ExecuteRader(), I can see that DBreader has - in the result view - as many objects as rows should be. How it comes that its known just after running?
Thank you

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

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

发布评论

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

评论(4

清醇 2024-08-18 03:57:42

DataReader 不包含行计数的原因是计算成本可能非常高。例如,假设您执行一个查询,返回今年输入且未删除的采购订单:

SELECT * FROM PurchaseOrders 
WHERE PurchaseDt > '2009-01-01'
AND IsDeleted = 0

并且您将此查询与 DataReader 结合使用并读出前 10 行。 SQL Server 根据请求将行“流”到客户端。每当您请求另一行时,SQL Server 将执行下一步的查询。因此,在您实际读出所有行之前,甚至 SQL Server 也不知道总行数。

The reason DataReader doesn't contain the rowcount is that it can be very expensive to calculate. For example, say you execute a query that returns purchase orders that were entered this year and not deleted:

SELECT * FROM PurchaseOrders 
WHERE PurchaseDt > '2009-01-01'
AND IsDeleted = 0

And you use this query with a DataReader and read out the first 10 rows. SQL Server "streams" rows to the client as it requests them. Whenever you ask for another row, SQL Server will execute the next step of the query. So not even SQL Server knows about the total number of rows before you've actually read out all the rows.

意中人 2024-08-18 03:57:42

要计算表中的行数(例如名称为 StudentTable),首先我使用以下 SQL 语句:

SELECT COUNT(*) FROM studentTable

我使用该语句作为 MySqlCommand 对象的命令文本。

然后,要使用 MySqlDataReader 对象(例如其名称为 reader)了解值(有多少行),我使用以下代码:

reader.GetString(0);

下面是我使用的代码:

...            
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT COUNT(*) FROM studentTable";
try
{
    conn.Open();
}
catch (Exception ex)
{
    label1.Content = ex.Message;
}

reader = command.ExecuteReader();
while (reader.Read())
{
    label1.Content = "";
    label1.Content = reader.GetString(0);
}

reader.Close();
conn.Close();

To count how many rows in a table (for instance the name is studentTable), firstly I use following SQL statement:

SELECT COUNT(*) FROM studentTable

I use that statement as the command text for the MySqlCommand object.

Then to know the value (how many rows) using an object of MySqlDataReader (for instance its name is reader) I use following code:

reader.GetString(0);

Below is the code that I use:

...            
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT COUNT(*) FROM studentTable";
try
{
    conn.Open();
}
catch (Exception ex)
{
    label1.Content = ex.Message;
}

reader = command.ExecuteReader();
while (reader.Read())
{
    label1.Content = "";
    label1.Content = reader.GetString(0);
}

reader.Close();
conn.Close();
情未る 2024-08-18 03:57:42

很简单,阅读器没有任何选项来限制现有的选项,数据表也没有选项。 Entonces lo que hacemos es pasar todos los datos del Reader al Datatable y trabajamos con este (se muestra como recuperar el Total de filas, y como recuperar un registro especico)。

String consulta = "SELECT * FROM xxx";
conexion.Open();
comando.CommandText = consulta;

reader = command.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(reader);

int nrofilas = dt.Rows.Count;

foreach (DataRow dr in dt.Rows)
{
    var value = dr["nameField"];
}

Es muy simple, el reader no tiene la opción de contar cuantas filas existe, el Datatable si tiene esa opción. Entonces lo que hacemos es pasar todos los datos del Reader al Datatable y trabajamos con este (se muestra como recuperar el total de filas, y como recuperar un registro especifico).

String consulta = "SELECT * FROM xxx";
conexion.Open();
comando.CommandText = consulta;

reader = command.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(reader);

int nrofilas = dt.Rows.Count;

foreach (DataRow dr in dt.Rows)
{
    var value = dr["nameField"];
}
_蜘蛛 2024-08-18 03:57:42

下面是我使用的功能。请随意根据您的需要进行调整。

    /// <summary>
    /// Counts the number of rows in a given table.
    /// </summary>
    /// <param name="tableName">The name of the table to query.</param>
    /// <param name="closeConnectionWhenDone">A flag indicating whether the connection should be closed once the query is executed.</param>
    /// <returns>The number of rows in the table.</returns>
    private static int GetNumRowsInTable(string tableName, bool closeConnectionWhenDone = false)
    {
        string selectQueryString = String.Format("select 1 from {0};", tableName);
        int numRows = 0;
        CommandBehavior behavior = closeConnectionWhenDone ? CommandBehavior.CloseConnection : CommandBehavior.Default;
        using (var command = new OdbcCommand(selectQueryString, ODBCHelper.Connection))
        using (var reader = command.ExecuteReader(behavior))
        {
            while (reader.Read())
            {
                numRows++;
            }
        }

        return numRows; 
    }

Below is the function that I use. Feel free to adjust it to your needs.

    /// <summary>
    /// Counts the number of rows in a given table.
    /// </summary>
    /// <param name="tableName">The name of the table to query.</param>
    /// <param name="closeConnectionWhenDone">A flag indicating whether the connection should be closed once the query is executed.</param>
    /// <returns>The number of rows in the table.</returns>
    private static int GetNumRowsInTable(string tableName, bool closeConnectionWhenDone = false)
    {
        string selectQueryString = String.Format("select 1 from {0};", tableName);
        int numRows = 0;
        CommandBehavior behavior = closeConnectionWhenDone ? CommandBehavior.CloseConnection : CommandBehavior.Default;
        using (var command = new OdbcCommand(selectQueryString, ODBCHelper.Connection))
        using (var reader = command.ExecuteReader(behavior))
        {
            while (reader.Read())
            {
                numRows++;
            }
        }

        return numRows; 
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文