【问题标题】:datatable load large data c#数据表加载大数据c#
【发布时间】:2017-06-14 22:25:59
【问题描述】:

在我的 c# mvc 4 应用程序项目中,我们需要从 sqlquery 中获取数据,然后填充到 C# 数据表中。 我们必须用超过 500 万行和 12 列填充数据表。

如果数据已

这是我正在使用的代码。

public DataTable GetTheData()
    {
        DataTable dtDataTablesList = new DataTable();
        string NewconnectionString ="Mycooectionstring";
        SqlConnection spContentConn = new SqlConnection(NewconnectionString);
        string sqlselectQuery = "select * from table";
        try
        {
            spContentConn.Open();
            SqlCommand sqlCmd = new SqlCommand(sqlselectQuery, spContentConn);
            sqlCmd.CommandTimeout = 0;
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.ExecuteNonQuery();
            SqlDataAdapter adptr = new SqlDataAdapter(sqlCmd);
            adptr.Fill(dtDataTablesList);
            spContentConn.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (spContentConn != null)
                spContentConn.Dispose();
        }
        return dtDataTablesList;
    }

【问题讨论】:

  • 你打算用 1M 记录做什么?你不能在任何地方展示它们。处理它们是数据库的用途。 Web 应用程序的运行速度永远不会比具有适当索引的编写良好的查询运行得更快。你想做什么?
  • 顺便说一句,您应该使用using 块而不是这个try/finally 和无关的catch,这只会破坏调用堆栈。
  • 我遇到过一种情况,我需要读取一个大表(5000 万行),然后通过批量上传写入另一个数据库。所以这确实有用。

标签: c# sql-server asp.net-mvc-4 ado.net


【解决方案1】:

为什么一次显示甚至需要 100 万条记录。您应该使用分页和限制记录数。我建议如果你有这么大的记录要显示,那么你应该一次最多显示 500 条记录。即使 500 条记录也很大,因此您可以减少 no。通过与您的团队和客户讨论来记录。

即使您设法在相当长的时间内加载所有这些记录,浏览器也将无法处理那么多记录并且可能会崩溃。但这只是我的假设,未经测试和验证。

分页可以参考下面的SQL代码

create table #TestTable(
 PK int primary key,
 Name nvarchar(50)
)

insert into #TestTable (PK, Name) values
(1, 'Name1'),
(4, 'Name4'),
(6, 'Name6')

select * from
(
 select row_number() over(ORDER BY pk ) SN, * from #TestTable
) temp
where SN>=1 and SN<=500

1 和 500 应该是动态的。在第 1 页你传递 1 和 500 在第 2 页你应该传递 501 和 1000。

【讨论】:

    猜你喜欢
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2021-02-16
    • 1970-01-01
    • 2012-02-11
    • 2013-01-01
    相关资源
    最近更新 更多