我有想要存储在db中的记录数。
数据库的架构是这样的
这样的人表:
CREATE TABLE IF NOT EXISTS Person (id INTEGER PRIMARY KEY, name TEXT)
和这样的文件表:
CREATE TABLE IF NOT EXISTS File (id INTEGER PRIMARY KEY, FileName TEXT,FilePath TEXT, PersonID NUMERIC CONSTRAINT person_file REFERENCES [Person]([id])ON DELETE NO ACTION ON UPDATE NO ACTION)
我使用此函数在两个表中执行插入
对于3700记录,这段代码在我的笔记本电脑上耗时140秒,
public long BuildDB(List<DB.Person> persons, List<DB.File> Files, FrmTrain form)
{
long result = -1;
try
{
long personID = 0;
using (SQLiteConnection sqlconnection = new SQLiteConnection("Data Source=" + DbPath + ";Version=3;"))
{
sqlconnection.Open();
SQLiteCommand PersonCommand = sqlconnection.CreateCommand();
SQLiteParameter personParam = new SQLiteParameter();
PersonCommand.CommandText = "INSERT INTO Person('Name') VALUES(?)";
PersonCommand.Parameters.Add(personParam);
SQLiteCommand FileCommand = sqlconnection.CreateCommand();
SQLiteParameter FileParam1 = new SQLiteParameter("@filename");
SQLiteParameter FileParam2 = new SQLiteParameter("@filepath");
SQLiteParameter FileParam3 = new SQLiteParameter("@personid");
FileCommand.CommandText = "INSERT INTO file(FileName,FilePath,PersonID) VALUES(@filename,@filepath,@personid)";
FileCommand.Parameters.Add(FileParam1);
FileCommand.Parameters.Add(FileParam2);
FileCommand.Parameters.Add(FileParam3);
for (int i = 0; i < persons.Count; i++)
{
using (SQLiteTransaction _SQLiteTransaction = sqlconnection.BeginTransaction())
{
personParam.Value = persons[i].Name;
PersonCommand.ExecuteNonQuery();
personID = sqlconnection.LastInsertRowId;
foreach (var item in Files.Where(f => f.PersonID == personID))
{
FileParam1.Value = item.FileName;
FileParam2.Value = item.FilePath;
FileParam3.Value = item.PersonID;
FileCommand.ExecuteNonQuery();
}
_SQLiteTransaction.Commit();
}
form.Progress();
}
sqlconnection.Close();
}
result = 1;
}
catch (Exception e)
{
result = 0;
throw;
}
return result;
}
首先,我在没有交易的情况下编写了该代码,大约需要500秒 我试图在事务中包装第二个ExecuteNonQuery,但不仅仅是改进了性能,它花了500秒
无论如何都要提高性能?
答案 0 :(得分:0)
尝试使用一个SQLiteTransaction,并且只为所有插入的人使用一个提交。
Error Code: 1054. Unknown column 'players.p_name' in 'where clause'