我试图使用executemany函数从一行中的所有行中获取一些WHERE约束
import sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS Genre (id INTEGER PRIMARY KEY, genre TEXT NOT NULL)')
values = [
(None, 'action'),
(None, 'adventure'),
(None, 'comedy'),
]
cur.executemany('INSERT INTO Genre VALUES(?, ?)', values)
ids=[1,2]
cur.executemany('SELECT * FROM Genre WHERE id=?', ids)
rows = cur.fetchall()
print rows
Run Code Online (Sandbox Code Playgroud)
cur.executemany('SELECT * FROM Genre WHERE id=?', ids)
sqlite3.ProgrammingError: You cannot execute SELECT statements in executemany()
Run Code Online (Sandbox Code Playgroud) 我正在试图弄清楚如何正确使用WHERE _ IN _语句
定义:
c.execute('''CREATE TABLE IF NOT EXISTS tab (
_id integer PRIMARY KEY AUTOINCREMENT,
obj text NOT NULL
) ;''')
Run Code Online (Sandbox Code Playgroud)
我正在尝试做这样的事情:
list_of_vars=['foo','bar']
statement="SELECT * FROM tab WHERE obj IN (?)"
c.execute(statement,"'"+"','".join(list_of_vars)+"'")
Run Code Online (Sandbox Code Playgroud)
或者,我也试过这个,直接评估上面的内容
statement="SELECT * FROM tab WHERE obj IN (?)"
c.execute(statement,"'foo','bar'")
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误.当我这样做时,它可以工作,但不建议这样做,因为它容易受到SQL注入攻击.
statement="SELECT * FROM tab WHERE obj IN ("+"'"+"','".join(statement)+"'"+")
Run Code Online (Sandbox Code Playgroud) 如何在Python中编写SQL查询来选择Python列表中的元素?
例如,我有 Python 字符串列表
Names=['name_1','name_2',..., 'name_n']
Run Code Online (Sandbox Code Playgroud)
和 SQLite_table。
我的任务是找到最短路线
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_1%'
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_2%'
...
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_n%'
Run Code Online (Sandbox Code Playgroud)