我正在使用C#/ .NET和SQLite的C#包装器。我正在尝试将两个SQLite数据库合并在一起,同时排除重复项。
我发现了这个,这是从几个不同的论坛问题中引用的。 http://old.nabble.com/Attempting-to-merge-large-databases-td18131366.html
我尝试过以下查询,我根据我提供的链接构建了这些查询,但它们导致异常,数据库根本没有合并,并且原始数据库不会发生任何变化。
attach 'c:\test\b.db3' as toMerge;
insert into AuditRecords select * from toMerge.AuditRecords;
这是我的查询代码。
public void importData(String fileLoc)
{
SQLiteTransaction trans;
string SQL = "ATTACH '" + fileLoc + "' AS TOMERGE";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Connection = connection;
connection.Open();
trans = connection.BeginTransaction();
int retval = 0;
try
{
retval = cmd.ExecuteNonQuery();
}
catch (Exception)
{
trans.Rollback();
MessageBox.Show("An error occurred, your import was not completed.");
}
finally
{
trans.Commit();
cmd.Dispose();
connection.Close();
}
SQL = "INSERT INTO SUBCONTRACTOR SELECT * FROM TOMERGE.SUBCONTRACTOR";
cmd = new SQLiteCommand(SQL);
cmd.Connection = connection;
connection.Open();
trans = connection.BeginTransaction();
retval = 0;
try
{
retval = cmd.ExecuteNonQuery();
}
catch (Exception)
{
trans.Rollback();
MessageBox.Show("An error occurred, your import was not completed.");
}
finally
{
trans.Commit();
cmd.Dispose();
connection.Close();
}
}
我的问题是,我做错了什么?是否有人熟悉insert命令?我不确定它是否会根据需要排除重复项。
答案 0 :(得分:10)
在SQLite中附加数据库时,需要在单个Connection / Transaction中执行每个语句(无论是插入,更新,删除)。不要在两者之间关闭连接。它应该在一次交易中完成。
试试这个
public void importData(String fileLoc)
{
string SQL = "ATTACH '" + fileLoc + "' AS TOMERGE";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Connection = connection;
connection.Open();
int retval = 0;
try
{
retval = cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("An error occurred, your import was not completed.");
}
finally
{
cmd.Dispose();
}
SQL = "INSERT INTO SUBCONTRACTOR SELECT * FROM TOMERGE.SUBCONTRACTOR";
cmd = new SQLiteCommand(SQL);
cmd.Connection = connection;
retval = 0;
try
{
retval = cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("An error occurred, your import was not completed.");
}
finally
{
cmd.Dispose();
connection.Close();
}
}