我是python的新手,我通過嘗試將連接變量分配給不同的.py文件中的函數而得到上述錯誤我試圖將連接設置為無,但沒有解決我的問題視圖.pyfrom datetime import datetimefrom flask import render_template, request, redirect, url_for, flashfrom FlaskWebProject1 import appimport jsonimport mysql.connectorfrom mysql.connector import Errorimport FlaskWebProject1.db @app.route('/')@app.route('/users')def users(): try: lstUsers = '' #connect to DB connection = db.get_connection() if connection.is_connected(): #db_Info = connection.get_server_info() #print("Connected to MySQL Server version ", db_Info) cursor = connection.cursor(dictionary=True) cursor.execute("select * from users;") record = cursor.fetchall() lstUsers = record #print("Your connected to database: ", record) except Error as e: print("Error while connecting to MySQL", e) finally: if (connection.is_connected()): cursor.close() connection.close() print("MySQL connection is closed") return render_template('users.html', title = 'Users Page', users = lstUsers)數據庫.py_connection = Nonedef get_connection(): global _connection if not _connection: _connection = mysql.connector.connect(user="bla@bla", password='bla', host="mysql.database.azure.com", port=3306, database='testdb') return _connection# List of stuff accessible to importers of this module. Just in case__all__ = [ 'getConnection' ]
1 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
錯誤顯示
NameError: name 'db' is not defined`
所以這是你的主要問題和其他問題的根源。
你有
import FlaskWebProject1.db
FlaskWebProject1.
所以你需要
connection = FlaskWebProject1.db.get_connection()
或者你應該導入
from FlaskWebProject1 import db
添加回答
舉報
0/150
提交
取消