SQLite3 记录操作

SQLite3 record manipulation

我正在 Python 使用 SQLite3 创建一个登录系统。我的代码选择了所有满足数据库中存储的用户名和密码的记录如下。

c.execute('SELECT * from foo WHERE username="%s" AND password="%s"' (username, password).
if c.fetchone is not None:
    do stuff

我不知道如何将该记录中的数据分配给函数内的局部变量,因此我可以检查它的值。在这种情况下,我想从我刚刚搜索的记录中检索用户组值,然后检查它是1还是2,以确定接下来调用哪个函数。

要调用fetchone方法,必须使用括号:

if c.fetchone() is not None:

如果您不将 fetchone() 的 return 值分配给变量,它就会丢失。

直接遍历游标会更好:

for row in c:
    print('value in first column: ', row[0])
    break
else:
    print('not found')

并且您应该 SELECT 只有一个列,这样可以更轻松地访问其值:

c.execute('SELECT usergroup FROM ...')
for (usergroup,) in c:
    print('group: ', usergroup)

如果有人输入密码 " OR "1"="1,他无论如何都会进入。要防止这样的 SQL injections,请始终使用参数:

c.execute('SELECT usergroup FROM foo WHERE username=? AND password=?',
          (username, password))
for (usergroup,) in c:
    print('group: ', usergroup)
    break
else:
    print('not found')