Python 连接数据库的问题
当我运行这个程序时,它不会改变数据库中的值。是因为选项部分出了问题还是有其他问题?我不知道是什么,我希望有人能帮我Python 连接数据库的问题,python,Python,当我运行这个程序时,它不会改变数据库中的值。是因为选项部分出了问题还是有其他问题?我不知道是什么,我希望有人能帮我 import sqlite3 def product_kopen(crsr): print ("Which product would you like to buy?") product = str(input("")) print ("And how many?") wanted_amount = int(input("")) crsr
import sqlite3
def product_kopen(crsr):
print ("Which product would you like to buy?")
product = str(input(""))
print ("And how many?")
wanted_amount = int(input(""))
crsr.execute("SELECT * FROM emp")
rows = crsr.fetchall()
for row in rows:
if row[0] == product:
actual_amount = int(row[1])
fetched_amount = actual_amount - wanted_amount
kopen = "UPDATE emp SET Amount = {amount} WHERE Product = '{name}' ".format(name=product,
amount=fetched_amount)
crsr.execute(kopen)
print("You have succesfully bought your product!", "\n")
def product_verkopen(crsr):
print ("Which product would you like to sell?")
sold_product = str(input(""))
print("And how many?")
wanted_sold_amount = int(input(""))
crsr.execute("SELECT * FROM emp")
rows = crsr.fetchall()
for row in rows:
if row[0] == sold_product:
actual_amount = int(row[1])
fetched_amount = actual_amount + wanted_sold_amount
kopen = "UPDATE emp SET Amount = {amount} WHERE Product = '{name}' ".format(name=sold_product,
amount=fetched_amount)
crsr.execute(kopen)
print("You have succesfully sold your product")
connection = sqlite3.connect("Stock.db", timeout=10)
crsr = connection.cursor()
connection.commit()
while True:
print("Welcome to this shop! choose your option", "\n",
"1. Buy a product.", "\n", "2. Sell a product")
option = int(input(""))
if option == 1:
product_kopen(crsr)
elif option == 2:
product_verkopen(crsr)
else:
print("This isn't a valid option", "\n")
continue
connection.close()
对数据库进行更改后,必须
commit
进行更改。sqlite3
默认情况下不commit
更改。每次执行cursor.execute(…)
,然后使用cursor.commit()
有关更多信息,请参见此处
crsr.execute(kopen)
crsr.commit()