SQLite名称错误:未定义名称“游标”

2024-10-03 06:20:26 发布

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

我正在尝试创建一个虚拟机,但在CLI中。我正在将SQLite用于登录数据,将来可能还会用于其他数据。遗憾的是,我不断地遇到这个错误,我不知道如何修复它。你们能帮帮我吗?我计划在修复此错误后在GitHub上发布此版本的第一个版本

from os import system, name
import sqlite3
from sqlite3 import Error

db_file = "userdata"

def create_connection(db_file):
    """ create a database connection to a SQLite database """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)
    except Error as e:
        print(e)
    finally:
        if conn:
            conn.close()

def clear():
    if name == 'nt':
        _ = system('cls')
    else: _ = system('clear')

def todolist():
    print("     Backlog | To-do                     | In progress     | Finished (coming in next update)")
    print("     --------|---------------------------|-----------------|---------------------------------")
    print("     -       | Register function         | SQLite database | Basis build")
    print("             | Forgot password function  |                 |")
    print("             | Login function            |                 |")

print("Made by The Celt")

print("Welcome back!")
print("Login (l)")
print("Register (r)")
print("Forgot password (fp)")

starterAction = input("What do you want to do? ")

create_connection(db_file)

if starterAction == "l":
    s.sleep(0.8)
    clear()
    insertUsername = input("Username:")
    for name in ('bar','foo'): 
        cursor.execute("SELECT rowid FROM components WHERE name = %s"%insertUsername, (name,))
        data=cursor.fetchone()
    if data is None:
        print("Could not find this username in the database!")
    else:
        insertPassword = input("Password: ")
        for name in ('bar','foo'): 
            cursor.execute("SELECT rowid FROM components WHERE name = %s"%insertPassword, (name,))
            data=cursor.fetchone()
        if data is None:
            print("Could not find this password in the database!")
        else:
            print("Welcome back, %s"%insertUsername)

elif starterAction == "r":
    s.sleep(0.8)
    clear()
    print("Still in progress!")
elif starterAction == "todolist":
    todolist()

Tags: nameinimportdbsqlitedataifconn
1条回答
网友
1楼 · 发布于 2024-10-03 06:20:26

这不是sqlite错误,而是python错误:您没有定义“游标”

您必须在db_文件附近的全局范围内定义conn和光标

db_file = "userdata"
conn = None
cursor = None

然后,在连接建立之后(在create_connection例程中),您需要添加游标创建

conn = sqlite3.connect(db_file)
cursor = conn.cursor()    

有关详细信息,请参见here

您从db中选择的方式也是错误的:

为了安全起见,尽可能使用绑定变量,例如(来自文档)

cur.execute('SELECT * FROM stocks WHERE symbol=?', t)  

如果仍然坚持连接查询字符串(我不建议这样做),则需要将正在搜索的值放在两个撇号内(我已将%s更新为“%s”)

... WHERE name = '%s'"%insertPassword, (name,) ...

相关问题 更多 >