【发布时间】:2015-02-04 10:54:29
【问题描述】:
我有一个非常大的 sql 插入文件,在 SQL 企业管理器中运行它时会引发“内存不足”错误。
我看到的建议是在插入的每 X 行中添加“GO”命令是“批处理”的。
我正在尝试编写一个小函数来读取文件,每 50 行添加一行文本“GO”
我编写的代码在运行时也抛出 System.OutOfMemoryException。
谁能建议一个更好的方法来编写我的代码来解决这个问题?
这是我写的:
public static void AddGo()
{
int currentline = 0;
string FilePath = @"C:\Users\trevo_000\Desktop\fmm89386.sql";
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(FilePath))
{
// add the current line
text.AppendLine(s);
// increase the line counter
currentline += 1;
if (currentline == 50)
{
text.AppendLine("GO");
currentline = 0;
}
}
using (var file = new StreamWriter(File.Create(@"C:\Users\trevo_000\Desktop\fmm89386Clean.sql")))
{
file.Write(text.ToString());
}
}
【问题讨论】:
-
使用
ReadLines而不是ReadAllLines并在你正在阅读的同一个循环中进行写入,而不是使用StringBuilder。这样一来,您一次不需要在内存中保留超过一行。 -
你的目标是什么?插入大量行?为什么是文件?不能使用 SqlCommand 吗?还是批量导入?
-
或者,您可以在具有足够 RAM 的计算机上使用 64 位构建的应用程序,并决定不值得为一次性脚本优化内存使用。
标签: c#