我有一个 SQL Server 2014 实例和一个用 C# 编写的客户端应用程序。
从这个应用程序中,我使用下面的代码检索数据。通过一些经验测试,似乎正在使用“服务器端游标”。对于我的特定用例,我想使用客户端游标。这怎么办? 如何让我的连接使用客户端游标?
<connectionStrings>
<clear/>
<add name="myDB"
connectionString="Server=SERVER\INSTANCE;Database=test"
providerName="System.Data.SqlClient" />
</connectionStrings>
C# 客户端代码:
using (var connection = OpenConnection())
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.my_stored_procedure";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
object retrievedObject = reader.GetValue(0);
// Use object...
}
}
}
}
有用的链接:
DataTable dt = new DataTable();
dt.Load(reader);
foreach (var row in dt.Rows) { /* Your data is in row now */}
将数据加载到 DataSet。 并且
DataSet 为您提供标准 IDataReader
:
public static IDataReader ExecuteReaderClient(SqlConnection connection, DbTransaction? transaction, String commandText)
{
DbCommand command = connection.CreateCommand();
command.CommandText = commandText;
if (transaction != null)
command.Transaction = transaction;
// Use an adapter to run the query
DbDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
// Ask the adapter to dump the results into a dataset
using (DataSet dataset = new DataSet());
adapter.Fill(dataset);
// Return the dataset as an IDataReader
return dataset.CreateDataReader();
}