"Delete from" 删除所有内容
"Delete from" deletes everything
我有一个 python 函数,它使用 name
属性作为条件删除 mysql table 中的一行:
def delete(table: str, name: str):
cursor.execute(f"DELETE FROM {table} WHERE name = {name}")
conn.commit()
我有一行的 name
属性等于“名称”。当我将此函数与“名称”一起使用时,它会删除 table.
中的每一行
我猜这与传递的字符串与属性相同有关。但是除了重命名属性之外,该问题的解决方案是什么?
首先,我认为您缺少名称周围的引号以及分号。
如需进一步阅读,您还应该看看 Python parameterized query and Prepared Statement
我同意评论,出于安全原因,table 不应作为注入参数!
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
cursor.execute(query, (name,))
conn.commit()`
编辑完整的工作示例:
import sqlite3
conn = sqlite3.connect("test")
query_create = '''CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
);'''
conn.execute(query_create)
query_insert = '''insert into projects (id, name, begin_date, end_date) values (1,"name","date","date")'''
conn.execute(query_insert)
query_select = '''select * from projects'''
cur = conn.execute(query_select)
print(cur.fetchall())
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
conn.execute(query, (name,))
delete('projects', 'name')
cur = conn.execute(query_select)
print(cur.fetchall())
给出输出:
[(1, 'name', 'date', 'date')]
DELETE FROM projects WHERE name = ?
[]
我有一个 python 函数,它使用 name
属性作为条件删除 mysql table 中的一行:
def delete(table: str, name: str):
cursor.execute(f"DELETE FROM {table} WHERE name = {name}")
conn.commit()
我有一行的 name
属性等于“名称”。当我将此函数与“名称”一起使用时,它会删除 table.
我猜这与传递的字符串与属性相同有关。但是除了重命名属性之外,该问题的解决方案是什么?
首先,我认为您缺少名称周围的引号以及分号。
如需进一步阅读,您还应该看看 Python parameterized query and Prepared Statement
我同意评论,出于安全原因,table 不应作为注入参数!
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
cursor.execute(query, (name,))
conn.commit()`
编辑完整的工作示例:
import sqlite3
conn = sqlite3.connect("test")
query_create = '''CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
);'''
conn.execute(query_create)
query_insert = '''insert into projects (id, name, begin_date, end_date) values (1,"name","date","date")'''
conn.execute(query_insert)
query_select = '''select * from projects'''
cur = conn.execute(query_select)
print(cur.fetchall())
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
conn.execute(query, (name,))
delete('projects', 'name')
cur = conn.execute(query_select)
print(cur.fetchall())
给出输出:
[(1, 'name', 'date', 'date')]
DELETE FROM projects WHERE name = ?
[]