问题描述
当我调用这段代码时:
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
进行一次新的数据库往返,还是在内部实现任何批量读取?
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?
我问是因为我刚刚读到 ODP.NET 在 OracleCommand
和 OracleDataReader
中都提供了 FetchSize
属性,我将其理解为单次往返数据库应预加载多少条记录.我想知道 SQL Server 是否以类似的方式工作,以及是否可以在某处配置一些类似的行为.我在 SqlCommand
、SqlDataReader
或 CommandBehavior
中没有找到任何此类配置.
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
.
推荐答案
数据以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.
这篇关于从 SQL Server 获取数据到 SqlDataReader 的工作原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!