[英]Ask for user input and insert in DB in python with sqlite3
At the moment I try to ask the user for input in Python, to enter some information (here: expenseID, expense, categoryID, date).目前我尝试要求用户在 Python 中输入,输入一些信息(这里:费用 ID、费用、类别 ID、日期)。 But I do not know were to start.
但是我不知道要开始。 No input validation is necessary at this step.
此步骤不需要输入验证。
I managed to access my database and INSERT something manually.我设法访问了我的数据库并手动插入了一些东西。 I tried several ways of the python
input
function but cannot use it as a placeholder in the SQL string.我尝试了 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
This is my idea:这是我的想法:
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
Finally I want to achieve that the user is asked for amount of expense, and afterwards for expense category.最后,我想实现要求用户提供费用金额,然后是费用类别。 ExpenseID and date should be added automatically.
应自动添加费用 ID 和日期。 Date format is year-month-day.
日期格式为年-月-日。 Thank you very much for advice.
非常感谢您的建议。
Use the input function to retrieve the user input使用输入函数检索用户输入
user_input = input("Expense Amount: ")
Then use placeholders with sqlite3然后在 sqlite3 中使用占位符
sql = "INSERT INTO TABLE (COLUMN) VALUES (?)"
conn.execute(sql, (user_input,))
**in response to your edit **回应您的编辑
You need to add placeholders instead of the variable names.您需要添加占位符而不是变量名称。
Something like this:像这样的东西:
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES (?, ?, ?, ?);"
conn.execute(script, (exp_ID,amount,category,date))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.