我如何使这个删除查询sqlite3在我的python项目中工作?

问题描述 投票:0回答:2

基本上这是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")
python-3.x sqlite sqlite3-python
2个回答
0
投票

这更接近您想要的。当然,此代码仍然无法按原样工作,因为该表在创建后不会立即包含任何产品。

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
投票

在您的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()关闭数据库连接。完成后关闭连接是一个很好的做法。

© www.soinside.com 2019 - 2024. All rights reserved.