Sqlite 事务,语法错误。在同一事务中插入和删除

发布于 2024-09-26 13:11:45 字数 1214 浏览 5 评论 0原文

我有一个要插入数据库的项目列表,但我不想要任何重复项。所以我删除所有项目并重新插入所有项目。这不是最有效的方法,但它的项目不多,所以它对我有用。但我在“插入”附近遇到语法错误。我执行以下操作:

DELETE FROM Settings WHERE Type = 'Extensions'
INSERT INTO Settings (Value, Type) Values ('img', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('avi', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mpg', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mkv', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mov', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('iso', 'Extensions')

并用以下命令执行它:

protected bool ExecuteCommand(string command, bool rollbackOnError)
{
    using (SQLiteTransaction transaction = DbConnection.BeginTransaction())
    {
        try
        {

            using (SQLiteCommand mycommand = new SQLiteCommand(DbConnection))
            {
                mycommand.CommandText = command;
                mycommand.ExecuteNonQuery();
                transaction.Commit();
            }
        }
        catch
        {
            if (rollbackOnError)
            {
                transaction.Rollback();
            }
            return false;
        }
    }
    return true;
}

I have a list of items that I want to insert into the database but I do not want any duplicates. So I delete all the items and reinsert all. It's not the most efficient way but it's not many items so it works for me. But I get syntax error near "Insert". I do the following:

DELETE FROM Settings WHERE Type = 'Extensions'
INSERT INTO Settings (Value, Type) Values ('img', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('avi', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mpg', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mkv', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('mov', 'Extensions')
INSERT INTO Settings (Value, Type) Values ('iso', 'Extensions')

And execute it with this:

protected bool ExecuteCommand(string command, bool rollbackOnError)
{
    using (SQLiteTransaction transaction = DbConnection.BeginTransaction())
    {
        try
        {

            using (SQLiteCommand mycommand = new SQLiteCommand(DbConnection))
            {
                mycommand.CommandText = command;
                mycommand.ExecuteNonQuery();
                transaction.Commit();
            }
        }
        catch
        {
            if (rollbackOnError)
            {
                transaction.Rollback();
            }
            return false;
        }
    }
    return true;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱情眠于流年 2024-10-03 13:11:45

您需要用分号分隔命令,不是吗?

我也不确定该命令是否能够运行多个语句。

You need to separate your commands with a semicolon, don't you?

Also I am not sure if the command is able to run multiple statements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文