如何解决 C# 中数据集的内存不足异常错误?

Huz*_*ifa 2 c# lucene exception out-of-memory dataset

我的数据库表中有数百万条记录,我试图将它们存储在数据集中(我使用数据集创建 Lucene 索引。)

问题是数据集无法处理数百万条记录,它给了我内存不足的异常。

public DataSet GetDataSet(string sqlQuery)
    {
        DataSet ds = new DataSet();
        SqlConnection sqlCon = new SqlConnection("Server=M-E-DB2;Database=IS;Trusted_Connection=True;");
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.Connection = sqlCon;
        sqlCmd.CommandType = CommandType.Text;
        sqlCmd.CommandText = sqlQuery;
        SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd);
        sqlAdap.Fill(ds);
        sqlCon.Close();
        return ds;

    }
Run Code Online (Sandbox Code Playgroud)

有人可以建议我处理内存不足异常的替代方法,请记住我的情况。

谢谢。

pro*_*pow 5

您可以使用SqlDataReader逐行获取

using (connection)
    {
        SqlCommand command = new SqlCommand();
        sqlCmd.Connection = sqlCon;
        sqlCmd.CommandType = CommandType.Text;
        sqlCmd.CommandText = sqlQuery;
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                 /// you can get values
            }
        }        
        reader.Close();
    }
Run Code Online (Sandbox Code Playgroud)

  • @John - _line by line_ 是您的解决方案。除非你只是存储它们,否则这是你的问题。 (3认同)