亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取“UnboundLocalError:分配前引用的局部變量'連接'”

獲取“UnboundLocalError:分配前引用的局部變量'連接'”

墨色風雨 2022-05-24 13:14:15
我是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


查看完整回答
反對 回復 2022-05-24
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號