简体   繁体   English

Python SQLITE3 插入和冲突时更新变量 - 语法问题?

[英]Python SQLITE3 Insert into and On conflict do update with variables - Syntax problem?

I am running this code in a method that is called in a for loop and passing to it 'text_body':我在 for 循环中调用的方法中运行此代码并将其传递给它'text_body':

*connecting to db*

cursor.execute('CREATE TABLE IF NOT EXISTS temp_data (temp_text_body text, id integer)')

cursor.execute('INSERT INTO temp_data(temp_text_body, id) VALUES (?, 1) ON CONFLICT (id) DO UPDATE '
               'SET temp_text_body = temp_text_body || (?)', (text_body, text_body))

*commiting connection*

My goal is to, on first time this is called to create a table and fill it with 'text_body', then on a second call add to the first 'text_body' second 'text_body' and so on.我的目标是,第一次调用它来创建一个表并用'text_body'填充它,然后在第二次调用时添加到第一个'text_body'第二个'text_body'等等。

I tried many combinations of this code, I was also trying to do it with UPDATE (and it was fine but UPDATE needs some data to actually start working).我尝试了此代码的许多组合,我也尝试使用 UPDATE 来完成(这很好,但 UPDATE 需要一些数据才能真正开始工作)。

When my code comes to this places it's just stop running, no error no anything.当我的代码到达这个地方时,它只是停止运行,没有任何错误。 Could some please let me know where I made a mistake?有人可以让我知道我在哪里犯了错误吗?

You cannot set 'ON CONFLICT' on a field which is not a primary key or which does not have a 'unique constraint'.您不能在不是主键或没有“唯一约束”的字段上设置“ON CONFLICT”。 Here's the error message I get when running your code:这是我在运行您的代码时收到的错误消息:

sqlite3.OperationalError: 
ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint

This in essence is because you cannot have a conflict if there is no Primary Key/ Unique constraint on that field.这实质上是因为如果该字段上没有主键/唯一约束,则不会发生冲突。

Under the assumption that you want id to be a unique Primary Key, I've created a working snippet:在您希望id成为唯一主键的假设下,我创建了一个工作片段:

import sqlite3

cursor = sqlite3.connect('stack_test.db')

cursor.execute('''CREATE TABLE IF NOT EXISTS temp_data 
                    (temp_text_body TEXT, 
                    id INTEGER PRIMARY KEY)''')

cursor.execute('''
                    INSERT INTO 
                        temp_data(temp_text_body, id) 
                    VALUES 
                        (?, 1) 
                    ON CONFLICT (id) DO UPDATE
                    SET 
                        temp_text_body = temp_text_body || (?)''',
            ("foo", "bar"))

cursor.commit()

I've also made some stylistic changes to how you write your query statements which I hope will made them a little easier for you to debug!我还对您编写查询语句的方式进行了一些风格上的更改,我希望这将使它们更容易调试!

Best of luck with the SQLite'ing, feel free to ask if any part of my answer is unclear:)祝您使用 SQLite'ing 好运,请随时询问我的答案是否有任何部分不清楚:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM