在REPLACE INTO中引用变量将引发sqlite3.OperationalError

thtygnil  于 2023-08-06  发布在  SQLite
关注(0)|答案(2)|浏览(107)

我的a脚本处理SQLite3表中的条目并进行一系列更改。最后一步是写出一个表,总结磁盘上哪些文件夹将受到更改的影响(更改将独立地写回文件系统中的底层文件)。

dbcursor.execute('SELECT DISTINCT __dirpath FROM alib where sqlmodded > 0')
dirpaths = dbcursor.fetchall()
dirpaths.sort()
dbcursor.execute('create table IF NOT EXISTS dirs_to_process (__dirpath blob PRIMARY KEY);')
for dirpath in dirpaths:
    dirpathstring = dirpath[0]
    dbcursor.execute(f"REPLACE INTO dirs_to_process (__dirpath) VALUES {dirpathstring}")

字符串
最后一行代码抛出一个错误:
dbcursor.execute(f“REPLACE INTO dirs_to_process(__dirpath)VALUES {dirpathstring}”)
sqlite3.OperationalError:near“/":语法错误
我试过了

dbcursor.execute("REPLACE INTO dirs_to_process (__dirpath) VALUES (?)", (dirpathstring))


但我无法解决它。

4ktjp1zp

4ktjp1zp1#

我找到了一个解决办法:

dbcursor.execute('SELECT DISTINCT __dirpath FROM alib where sqlmodded > 0')
dirpaths = dbcursor.fetchall()
dirpaths.sort()
dbcursor.execute('CREATE TABLE IF NOT EXISTS dirs_to_process (__dirpath blob PRIMARY KEY);')
for dirpath in dirpaths:

    record = (f'REPLACE INTO dirs_to_process (__dirpath) VALUES ("{dirpath[0]}")')
    dbcursor.execute(record)

字符串

ih99xse1

ih99xse12#

你可以这样做:

import sqlite3

connection = sqlite3.connect('test.db')
dbcursor = connection.cursor()

dbcursor.execute('SELECT DISTINCT __dirpath FROM alib')
dirpaths = dbcursor.fetchall()
dirpaths.sort()

dbcursor.execute('create table IF NOT EXISTS dirs_to_process (__dirpath blob PRIMARY KEY);')

for dirpath in dirpaths:
    dirpathstring = dirpath[0]
    print(f'{dirpath} => {dirpathstring}')
    dbcursor.execute(f"REPLACE INTO dirs_to_process (__dirpath) VALUES (?)", (dirpathstring,))

connection.commit()
print('Done')

字符串
注意replace命令是如何运行的。查询将是:

replace into table (column) values (?)


我们将在查询后向execute命令提供一个set,如下所示:

('/dir1',)


最后,我们将提交数据,以便将数据保存在DB中。
我在alib中插入了以下数据:

  • /dir1
  • /dir1/dir2
  • /dir1/dir3/

当我运行python3 test.py时,我将得到以下输出:
python3 test.py('/dir1',)=> /dir1('/dir1/dir2',)=> /dir1/dir2('/dir1/dir3/',)=> /dir1/dir3/
当我使用sqlite3 test.db查询SQLite并运行:

sqlite> select * from dirs_to_process;

-- I get the following output
/dir1
/dir1/dir2
/dir1/dir3/


希望这对你有帮助。给予看
只要知道你甚至可以这样做:

for dirpath in dirpaths:
    dbcursor.execute(f"REPLACE INTO dirs_to_process (__dirpath) VALUES (?)", dirpath)


并消除对dirpathstring = dirpath[0]的需要,除非您绝对需要这样做。

相关问题