提问人:Honey 提问时间:11/3/2023 最后编辑:Honey 更新时间:11/3/2023 访问量:39
如何使此删除查询SQLite3在我的Python项目中工作?
how i can make this delete query sqlite3 work in my python project?
问:
基本上这是 sqlite3 中删除的语法,我怎样才能让它在这个 def(函数)中工作? 例如,当我输入 2 时,我想删除 ID 号 1
import sqlite3
connection = sqlite3.connect("store.db")
cur = connection.cursor()
try:
cur.execute("CREATE TABLE store(id int, name var(250), price int, manufacturer_country var(250));")
except Exception as e:
print('table creation failed')
def delete_a_product():
global cur
global connection
id = int(input("enter product id: "))
query = 'DELETE FROM store WHERE id=?'
cur.execute(query)
connection.commit()
global products
product_index = int(input('enter a product_index: '))
lower_bound = 1
upper_bound = len(products)
if product_index >= lower_bound and product_index <= upper_bound:
del products[product_index-1]
else:
print("Enter a valid price")
答:
0赞
Tim Roberts
11/3/2023
#1
这更接近你所追求的。当然,此代码仍然无法按原样工作,因为在您创建表格后,该表格不会立即包含任何产品。
import sqlite3
connection = sqlite3.connect("store.db")
cur = connection.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store(id int, name var(250), price int, manufacturer_country var(250));")
def delete_a_product(product):
query = 'DELETE FROM store WHERE id=?'
cur.execute(query, (product,))
connection.commit()
product_index = int(input('enter a product_index to delete: '))
delete_a_product(product_index-1)
0赞
Subarnadip Pal
11/3/2023
#2
在 delete_a_product 函数中,存在一些逻辑错误和 SQLite3 命令的误用,需要纠正这些错误,以使函数按预期工作。下面是函数的优化版本:
import sqlite3
# Connect to the database
connection =
sqlite3.connect("store.db")
cur = connection.cursor()
# Try to create a table
try:
cur.execute("CREATE TABLE store(id
INTEGER PRIMARY KEY, name TEXT, price
INTEGER, manufacturer_country TEXT);")
except sqlite3.OperationalError as e:
print('Table already exists:', e)
def delete_a_product():
global cur
global connection
# Get user input for the product id
id_to_delete = int(input("Enter
product id: "))
# Create the query string
query = 'DELETE FROM store WHERE id=?'
# Execute the query with the id to
delete
cur.execute(query, (id_to_delete,))
connection.commit()
print(f'Product with id {id_to_delete}
has been deleted.')
# Call the function
delete_a_product()
# Close the database connection
connection.close()
修改了 CREATE TABLE 语句,将 id 设置为 INTEGER PRIMARY KEY。这样,SQLite将自动递增id字段,确保唯一性。
更改了delete_a_product功能以从用户输入中获取id_to_delete。
cur.execute() 行现在包含一个元组,其中 id_to_delete 作为参数来替换 ?查询字符串中的占位符。这就是在SQLite中将参数传递给查询以防止SQL注入攻击的方式。
删除了与 product_index、lower_bound、upper_bound 和 products 数组相关的代码,因为不清楚您打算如何处理这些数组,并且它们对于从数据库中删除记录不是必需的。
调用 delete_a_product 后,脚本现在将使用 connection.close() 关闭数据库连接。完成后关闭连接是一种很好的做法。
下一个:Python 消息框异常处理
评论
cur.execute(query, (id,))
delete_products[product_index-1]
def delete_a_product(product):