Python:sqlite3.OperationalError:near“<”:语法错误(使用html源代码更新sqlite3字段)

2024-04-26 20:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改sqlite表itemNotesnote字段中的sometext(匹配所有大小写组合,如sometextSOMETEXTSOmeTExt)。你知道吗

因为sqlite不支持不区分大小写的更新(我已经问了2个问题herehere),所以我使用pythonregex。你知道吗

但是我得到了这个错误:sqlite3.OperationalError: near "<": syntax error匹配线的cursor.execute(f'REPLACE

我的代码中没有<,所以我认为它来自包含html源代码的note字段。你知道吗

这是我的密码:

keyword ="sometext"
replacement_word="abc"

# load sqlite3
db = sqlite3.connect(path_to_sqlite)
cursor = db.cursor()

# search for all therm
cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')
print("\nfetch one:")
# itemID_list = cursor.fetchone()

# pour chacun des result, change
for row in cursor.fetchall():
    # print(each)
    row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
    row_regex_replaced = row_regex.sub(replacement_word, row[2])

    rowindex = row[0]
    cursor.execute(
        f'REPLACE INTO itemNotes (note) VALUES ({row_regex_replaced}) where itemID = {rowindex}')

在查找了“sql注入”之后,我得出了以下结论:

sql = "REPLACE INTO itemNotes (note) VALUES (?) where itemID = (?)"
data = (row_regex_replaced, rowindex,)
cursor.execute(sql, data)

但是现在我得到了这个错误:sqlite3.OperationalError: near "where": syntax error


Tags: reexecutesqlitesqlite3cursorkeywordreplaceregex
1条回答
网友
1楼 · 发布于 2024-04-26 20:37:01

sqlite doc

The REPLACE command is an alias for the "INSERT OR REPLACE" variant of the INSERT command.

INSERT没有WHERE子句。查询需要写成“常规”插入,系统将“决定”是否替换。类似于INSERT into itemNotes (itemID,note) VALUES (?,?)。(注意,上面示例中data列表的顺序需要更改)。你知道吗

相关问题 更多 >