【发布时间】:2018-02-27 09:04:59
【问题描述】:
我该如何解决这个问题? 流程如下。
- 导入 csv 文件
- 向 sqlite 插入数据(100 万行)
异常是“System.Data.SQLite.OutOfMemoryException” 我使用了“beginTransaction”和“Commit” CSV文件内存为118MB 我什么都试过了。但我不能解决这个问题
这是我的源代码。 请帮忙。
OpenFileDialog file = new OpenFileDialog();
file.Filter = "(*.csv)|*.csv";
file.ShowDialog();
string filename = file.FileName;
string fileNameNoEx = Path.GetFileNameWithoutExtension(filename);
for (int j = 0; j < ListBox.Items.Count; j++)
{
if (fileNameNoEx.Equals(ListBox.Items[j]))
{
return;
}
}
DirectoryInfo di = new DirectoryInfo("C:/sqlite");
FileInfo fi = new FileInfo("C:/sqlite/SQLiteEx.db");
if (!di.Exists)
{
di.Create();
}
if (!fi.Exists)
{
SQLiteConnection.CreateFile("C:/sqlite/SQLiteEx.db");
}
SQLiteConnection conn = new SQLiteConnection("data source = C:/sqlite/SQLiteEx.db;PRAGMA synchronous = OFF; PRAGMA journal_mode = WAL;");
conn.Open();
string sql = "";
StreamReader sr = new StreamReader(filename);
int i = 0;
using (SQLiteTransaction tr = conn.BeginTransaction())
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
string[] cols = line.Split(',');
string fieldName = "";
string colData = "";
if (i == 0)
{
for (int j = 0; j < cols.Length; j++)
{
if (j == 0)
{
fieldName = "'" + cols[0] + "' TEXT";
}
else
{
fieldName = fieldName + ",'" + cols[j] + "' TEXT";
}
}
sql = "CREATE TABLE IF NOT EXISTS " + fileNameNoEx + "(" + fieldName + ");";
SQLiteCommand command = new SQLiteCommand(sql, conn);
int result = command.ExecuteNonQuery();
}
else
{
for (int j = 0; j < cols.Length; j++)
{
if (j == 0)
{
colData = cols[0];
}
else
{
colData = colData + "," + cols[j];
}
}
sql = "INSERT INTO " + fileNameNoEx + " VALUES (" + colData + ");";
SQLiteCommand command = new SQLiteCommand(sql, conn);
int result = command.ExecuteNonQuery();
}
i++;
}
tr.Commit();
}
sr.Close();
conn.Close();
【问题讨论】:
-
您是否有特殊原因要在单个事务中执行所有插入操作?
-
由于插入操作不依赖任何其他数据库数据,我不确定是否应该有事务。请记住事务是为了存储所有更改以允许在一个最终命令中恢复或提交它们,所以是的,在此之前所有这些都保存在内存中。
-
有使用sqlcollect数组的原因吗?我相信这是OOM异常的根本原因。尝试删除它并尝试一下。让我知道。仅供参考,您的代码还有其他问题,人们已经在答案部分提出了它。请考虑他们。
标签: c# sqlite csv transactions out-of-memory