如何将表上fetchall()的输出仅限于值?

2024-10-03 11:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

def credential_check(username, password):
            conn = sqlite3.connect('pythontkinter.db')
            c = conn.cursor()
            idvalue = c.execute('''SELECT ID FROM userdetails WHERE username = "{0}"'''.format(username)).fetchall()
            print(idvalue)

我希望在userdetails表中将ID的值赋给变量idvalue,该变量位于输入的username=userdetails username的行中,但是当我使用这个fetchall()时,我得到的是[('0',)],而不是仅仅0。你知道吗

我该怎么做呢?你知道吗

谢谢


Tags: 功能iddbdefcheckconnectusernamepassword
1条回答
网友
1楼 · 发布于 2024-10-03 11:14:00

如果只需要一个值,可以使用fetchone()。但是,结果仍将作为元组返回,只是没有列表。你知道吗

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS testing(id TEXT)''')
conn.commit()

c.execute("""INSERT INTO testing (id) VALUES ('0')""")
conn.commit()

c.execute("""SELECT id FROM testing""")
data = c.fetchone()
print data
#  > (u'0',) 

如果要使用fetchall()限制返回值的数量,也可以使用^{}。你知道吗

更重要的是,不要这样格式化查询。习惯使用?占位符作为一种习惯,这样您就不会受到SQL注入的攻击。你知道吗

idvalue = c.execute("""SELECT ID FROM userdetails WHERE username = ?""", (username,)).fetchone()

相关问题 更多 >