C# Sqlite查询:如何处理合并以及更新时如何处理

C# Sqlite查询:如何处理合并以及更新时如何处理,c#,sqlite,C#,Sqlite,我有两个使用此代码成功合并的sqlite表 private static void MergeDatabase(string table, string mainDatabase, string mergeDatabase) { string SQL = "ATTACH '" + mergeDatabase + "' AS TOMERGE"; SQLiteCommand cmd = new SQLiteCommand(SQL); stri

我有两个使用此代码成功合并的sqlite表

private static void MergeDatabase(string table, string mainDatabase, string mergeDatabase)
    {
        string SQL = "ATTACH '" + mergeDatabase + "' AS TOMERGE";
        SQLiteCommand cmd = new SQLiteCommand(SQL);

        string databasePath = mainDatabase;
        string connectionString = string.Format("Data Source={0}; Version=3", databasePath);
        SQLiteConnection connection = new SQLiteConnection(connectionString);

        cmd.Connection = connection;
        connection.Open();
        int retval = 0;
        try
        {
            retval = cmd.ExecuteNonQuery();
        }
        catch (Exception)
        {
            Console.WriteLine(DateTime.Now.ToString("yy.MM.dd HH:mm:ss") + " An error occurred, your import was not completed.");
        }
        finally
        {
            cmd.Dispose();
        }

        SQL = "INSERT INTO " + table + " SELECT * FROM TOMERGE." + table + " WHERE Name NOT IN (SELECT Name FROM " + table + ")";
        cmd = new SQLiteCommand(SQL);
        cmd.Connection = connection;
        retval = 0;
        try
        {
            retval = cmd.ExecuteNonQuery();
        }
        catch (Exception)
        {
            Console.WriteLine(DateTime.Now.ToString("yy.MM.dd HH:mm:ss") + " An error occurred, your import was not completed.");
        }
        finally
        {
            cmd.Dispose();
            connection.Close();
        }
    }
结果:


是的,它合并了,但是,如果我只是像这样更新表2中的一些项目,我不知道如何处理


正如您刚才从表2中看到的更新项目


我想要的东西,可以处理合并,也可以处理当我更新表2中的一些项目时,它只会更新表1,而不是添加它们

我相信以下内容将满足您的要求:-

INSERT OR REPLACE INTO table1 SELECT * FROM table2 WHERE id||name NOT IN (SELECT id||name FROM table1);
这基本上会添加
或REPLACE
,这将在出现唯一或主键约束冲突时替换该行,而不是插入该行

WHERE子句稍微更改为测试id和名称,而不仅仅是名称

名称基于示例,即表1和表2


这确实假设ID列是rowid的别名,并且ID的管理使它们保持同步。

到底应该发生什么?是否应覆盖具有相同ID的行,是否应追加具有不存在ID的行?(在
表1中应删除缺少的ID
?)结果应该是,当表2中的某些项目使用表1中相同的ID进行更新时,它将只更新表1中的项目。请显示表定义。有索引吗?