简体   繁体   English

如何使用ado.net从SQL Server获取大量数据?

[英]How get huge data from sql server using ado.net?

I'm getting error while fetching the data 提取数据时出现错误

Exception of type 'System.OutOfMemoryException' was thrown 引发了类型'System.OutOfMemoryException'的异常

Error getting line is dataAdapter.Fill(dataTable); 错误获取行是dataAdapter.Fill(dataTable);

(2826000) records count in my table. (2826000)条记录在我的表格中。

here is the code i'm using. 这是我正在使用的代码。

var dataTable = new DataTable();
var DicTableNameAndValues = new Dictionary<string, object>();

using (var connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    var dataQuery = "SELECT * FROM  " + table;
    using (var command = new SqlCommand(dataQuery, connection))
    {
        var dataAdapter = new SqlDataAdapter(command);
        dataAdapter.Fill(dataTable);
        var result = dataTable.AsEnumerable().Skip(skip).Take(pageSize).ToList().Select(c => c.ItemArray);
        DicTableNameAndValues.Add(table, result);

    }
}

You can get a certain number of records as required by your application instead of all the records. 您可以获取应用程序所需的一定数量的记录,而不是所有记录。 You can create a stored procedure something to the effect of the following. 您可以创建存储过程以达到以下效果。

--Create a stored procedure with following parameters
DECLARE @skip int, @pagesize int

--Added testing values
SELECT @skip = 4, @pagesize = 3

--Give @tbl with your table name. 
/*If you already have an identity key then probably row_number function might not 
be required. But if the records are getting deleted as well then row_number is a
better option*/
SELECT * FROM
(SELECT ROW_NUMBER() over(ORDER BY Your_Col) AS ROWNUM, * FROM @tbl) as tbl
WHERE ROWNUM BETWEEN (@skip * @pagesize) + 1 and (@skip + 1) * (@pagesize)

Hope this helps. 希望这可以帮助。

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

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