首页 > 解决方案 > Sqlite 连接的 Python NameError

问题描述

我正在使用 Tkinter 和 Sqlite 作为数据库构建基于 GUI 的 python 应用程序。在主页(一个 Tkinter 窗口)上,有多个选项可供用户选择一个,这将使他进入一个新的 Tkinter 窗口,他可以在其中自定义和执行 SQL 查询。在代码片段中,我只添加了 Quer1.py。

当我单独运行 Query1.py 时,GUI 和 Sqlite 连接工作得很好。但是,当我尝试从 Homepage.py 窗口运行它时,我遇到了NameError: name 'sqliteConnection' is not defined在函数Query1.py内部被调用的get_all_data()情况。

主函数中的 sqlite 连接输出完美地为我提供了 SQL 版本,但是当我在函数内部调用它时代码中断。

有什么建议可以解决这个问题吗?

查询1.py

from SqlConnection import sqliteConnection

def get_all_data():
    cursor = sqliteConnection.cursor()
    sqlite_select_Query = ("some sql query")
    cursor.execute(sqlite_select_Query)
    data = (row for row in cursor.fetchall())
    cursor.close()
    root = tk.Tk()
    root.mainloop()

if __name__ == '__main__':
    window = tk.Tk()
    window.title("Window Title")
    cursor = sqliteConnection.cursor()
    sqlite_select_Query = "select sqlite_version();"
    cursor.execute(sqlite_select_Query)
    record = cursor.fetchall()
    print("SQLite Database Version is: ", record)
    btn = Button(window, text='Fetch Query1', command=get_all_data)
    btn.grid(column=1, row=1)
    window.mainloop()
    sqliteConnection.close()

主页.py

from tkinter import *
import tkinter as tk    
import Query1

def get_Q1():
    exec(open('Query1.py').read())

if __name__ == '__main__':
    window = tk.Tk()
    window.title("Homepage")
    window.geometry('1000x700')
    btn1 = Button(window, text='1. Orchestra(s)+country', height=7, width=60, command=get_Q1)
    btn1.grid(column=1, row=1)
    window.mainloop()

SqlConnection.py

import sqlite3
try:
    sqliteConnection = sqlite3.connect('test_1.db')
    cursor = sqliteConnection.cursor()
    print("Database created and Successfully Connected to SQLite")

    sqlite_select_Query = "select sqlite_version();"
    cursor.execute(sqlite_select_Query)
    record = cursor.fetchall()
    print("SQLite Database Version is: ", record)
    cursor.close()

except sqlite3.Error as error:
    print("Error while connecting to sqlite", error)

输出

Database created and Successfully Connected to SQLite
SQLite Database Version is:  [('3.28.0',)]
SQLite Database Version is:  [('3.28.0',)]
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\stanl\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "<string>", line 6, in get_all_data
NameError: name 'sqliteConnection' is not defined

标签: pythonsqlitetkinter

解决方案


推荐阅读