【问题标题】:SQLite3 record manipulationSQLite3 记录操作
【发布时间】:2017-10-08 14:12:21
【问题描述】:

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

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

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

【问题讨论】:

  • fetchone 是一个方法;你调用它,它会返回数据。
  • 那我该如何使用fetchone呢?
  • 就像任何其他方法一样。 data = c.fetchone().

标签: python database sqlite data-manipulation


【解决方案1】:

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

if c.fetchone() is not None:

如果你不将fetchone()的返回值赋给一个变量,它就会丢失。

直接在光标上迭代会更好:

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

而且你应该只选择一个列,这使得访问它的值更容易:

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多