此刻,我尝试要求用户在Python中输入内容,以输入一些信息(此处:expenseID,费用,categoryID,日期)。但是我不知道是要开始。在此步骤中无需输入验证。
我设法访问我的数据库并手动插入某些内容。我尝试了python input
函数的几种方法,但是不能将其用作SQL字符串中的占位符。
import sqlite3
with sqlite3.connect('Expenses.sqlite') as conn:
# INSERT MANUALLY
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES ('103', '43625.5', '5', '2019-01-20');"
conn.execute(script) # execute the script
conn.commit() # commit changes to the file
# INSERT USER INPUT ???
pass
这是我的主意
with sqlite3.connect('Expenses.sqlite') as conn:
amount = input("What is the amount?")
script = "SELECT * FROM Category;"
conn.execute(script)
print(script)
category = input("What is the category?")
exp_ID = "SELECT LAST ExpenseId FROM Expense);"
date = datetime.date.today()
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES (exp_ID, amount, category, date);"
conn.execute(script)
conn.commit()
pass
最后,我要实现的是要求用户提供费用金额,然后是费用类别。 ExpenseID和日期应自动添加。日期格式为年-月-日。非常感谢您的建议。
答案 0 :(得分:2)
使用input函数检索用户输入
sql = "INSERT INTO TABLE (COLUMN) VALUES (?)"
conn.execute(sql, (user_input,))
然后将placeholders与sqlite3一起使用
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES (?, ?, ?, ?);"
conn.execute(script, (exp_ID,amount,category,date))
**响应您的修改
您需要添加占位符而不是变量名。
类似这样的东西:
$request->session()->put('key', 'value');