如何从 SQL Server 获取数据到 SqlDataReader?

发布于 2024-11-07 23:46:25 字数 724 浏览 1 评论 0原文

当我调用这段代码时:

using (var connection = new SqlConnection(connectionString))
{
    var command = new SqlCommand("SELECT * FROM Table", connection);
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // Do something here
        }
    }
}

内部发生了什么?这在网络层面如何运作?每次调用 Read 时,它都会对数据库进行新的往返吗?或者内部是否实现了批量读取?

我之所以这么问,是因为我刚刚读到 ODP.NET 在 OracleCommandOracleDataReader 中提供了 FetchSize 属性,我将其理解为记录数量的定义应通过单次往返数据库进行预加载。我想知道 SQL Server 是否以类似的方式工作,以及是否有一些类似的行为可以在某处配置。我在 SqlCommandSqlDataReaderCommandBehavior 中没有找到任何此类配置。

When I call this code:

using (var connection = new SqlConnection(connectionString))
{
    var command = new SqlCommand("SELECT * FROM Table", connection);
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // Do something here
        }
    }
}

what happens internally? How does this work on a network level? Will it make a new round trip to database for each call to Read or is there any batch read implemented internally?

I'm asking because I just read that ODP.NET provides FetchSize property in both OracleCommand and OracleDataReader which I understand as definition of how many records should be preloaded by single round trip to the database. I wonder if SQL Server works in similar fashion and if there is some similar behavior which can be configured somewhere. I didn't find any such configuration in SqlCommand, SqlDataReader or CommandBehavior.

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

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

发布评论

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

评论(2

林空鹿饮溪 2024-11-14 23:46:25

数据以 SqlConnection.PacketSize 属性中大小的数据包从 sql server 流式传输到客户端。如果您的客户端无法足够快地读取结果,则网卡上的缓冲区已满,协议会检测到这一点并停止接收,这反过来会使 sql server 的网卡发送缓冲区已满,并停止发送任何和所有数据。如果您想深入了解协议级别,请查看 TDS 协议

the data is streamed from sql server to the client in the packets of the size in SqlConnection.PacketSize property. If your client can't read results fast enough the buffer on the network card gets filled up, the protocol detects this and stops receiving which in turn makes sql server's network card send buffer full and it stops sending any and all data. if you want to go down to the protocl level then check out TDS protcol.

流星番茄 2024-11-14 23:46:25

我相信网络通信的确切细节取决于代码示例之外的许多因素,部分原因是 SQL Server 连接池,但我认为您正在寻找 SqlConnection.PacketSize 属性(MSDN)。

I believe the exact details of the network communications are dependent on a lot of things outside of your code sample, in part because of the SQL Server Connection Pooling, but I think you're looking for the SqlConnection.PacketSize property (MSDN).

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