[英]How do I assign a single value from SQLite (according to two other values) to my Python variable?
I'm trying to create a simple online login form using Python and SQLite3: 我正在尝试使用Python和SQLite3创建一个简单的在线登录表单:
user_email = request.forms.get("email")
user_password = request.forms.get("password")
connection = sqlite3.connect("/home/hassanrashid/mysite/users.db")
c = connection.cursor()
c.execute("SELECT UserName from account WHERE UserEmail=? AND UserPassword=?", (user_email, user_password))
The email and password values entered into the html form are assigned to the user_email
and user_password
variables respectively. 输入到html表单中的电子邮件和密码值分别分配给
user_email
和user_password
变量。 What I'm trying to do is, once the user logs in, he is greeted with a welcome message ("Welcome, UserName!"). 我要做的是,一旦用户登录,就会收到欢迎消息(“ Welcome,UserName!”)。
My question is, how do I assign the UserName
value from my SQLite database table to my Python variable user_name
? 我的问题是,如何将SQLite数据库表中的
UserName
值分配给Python变量user_name
?
I've also tried this code: 我也尝试过以下代码:
user_name = c.execute("SELECT UserName from account WHERE UserEmail=?", (user_email)).fetchone()
But that gives me an error: "Incorrect number of bindings supplied. The current statement uses 1, and there are 15 supplied."
但这给了我一个错误:
"Incorrect number of bindings supplied. The current statement uses 1, and there are 15 supplied."
There are 15 rows in my database. 我的数据库中有15行。 I'm assuming that the criteria (
WHERE UserEmail=?
) isn't being applied. 我假设未应用标准(
WHERE UserEmail=?
)。
How do I fix this? 我该如何解决?
user_name = c.execute("SELECT UserName from account WHERE UserEmail=?", (user_email)).fetchone()
Two issues with this: 这有两个问题:
(user_email)
is not a tuple, so you are not passing a 1-element tuple to execute()
. (user_email)
不是元组,因此您没有将1元素元组传递给execute()
。 Instead, pass (user_email,)
to make a 1-element tuple. 而是传递
(user_email,)
组成一个1元素的元组。
The return value of fetchone()
will return the whole result row as a tuple. fetchone()
的返回值将以元组的形式返回整个结果行。 If there is only one column in the row, you will still get a 1-element tuple back. 如果行中只有一列,您仍将返回一个1元素元组。 You need to unpack the tuple first in order to fix this:
您需要先打开元组的包装才能解决此问题:
query = "SELECT UserName from account WHERE UserEmail=?"
result = c.execute(query, (user_email,))
# either store the row tuple first
row = result.fetchone()
user_name = row[0]
# or you could unpack the tuple immediately (note the trailing comma)
user_name, = result.fetchone()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.