python - 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
解决方案
推荐阅读
- c# - MS Word 通过 COM-object 接口将图像添加到基板/水印
- reactjs - 反应路由器:动态 url id
- php - 如何在 Laravel 中访问验证错误属性名称?
- vb.net - 即使使用通配符也无法从外部访问 VB.net 服务器
- javascript - 在构造函数中访问构造函数的属性
- python - 查找第一次出现的代码,如果没有出现则返回 0,然后将新列附加到 csv (python)
- visual-studio-code - 在顶部显示我的自定义 vscode 语言扩展建议
- java - 如何使 mediaView 始终出现在 JavaFX 中 BorderPane 的中心?
- alfresco - 添加文档时,在露天创建的模型不会自动显示
- python-3.x - 从熊猫数据框中仅提取数字和字符串