![](/img/trans.png)
[英]Python - AttributeError: 'NoneType' object has no attribute 'cursor'
[英]Python - AttributeError: 'NoneType' object has no attribute 'cursor' python flask
我正在嘗試使用數據庫中的數據在我的 webapp 中填充課程選擇字段。 這是我的嘗試。
這種形式`
class StudentForm(FlaskForm):
idnumber = StringField('ID Number', [validators.DataRequired(), validators.Length(min=9, max=9)])
fname = StringField('First Name', [validators.DataRequired(), validators.Length(max=50)])
mname = StringField('Middle Name', [validators.Length(max=50)])
lname = StringField('Last Name', [validators.DataRequired(), validators.Length(max=50)])
gender = SelectField('Gender', choices=gengen)
yearlvl = SelectField('Year Level', choices= year_level)
course = SelectField('Course', choices= models.Courses.populate())
submit = SubmitField("Save")
`
@classmethod
def populate(cls):
curs = mysql.connection.cursor()
sql = curs.execute("SELECT COURSEID from courses")
if sql > 0:
result = curs.fetchall()
return result
'
當我運行程序時出現此錯誤
`
File "C:\laragon\SISwebapp\webapp\students\forms.py", line 15, in StudentForm
course = SelectField('Course', choices= models.Courses.populate())
File "C:\laragon\SISwebapp\webapp\models.py", line 87, in populate
curs = mysql.connection.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'
`我似乎無法弄清楚出了什么問題..
編輯:
這部分工作正常:
def all(cls):
cursor = mysql.connection.cursor()
sql = "SELECT * from courses"
cursor.execute(sql)
result = cursor.fetchall()
return result
它從數據庫表中獲取所有數據。 但是,僅選擇一列時它不起作用。 請多多包涵。 我對這種東西很陌生。
要創建一個 cursor,請使用連接 object 的cursor()
方法:
cnx = mysql.connector.connect(database='Hello_World')
cursor = cnx.cursor()
在那種特殊情況下,您的mysql.connection
object 似乎是None
。 這就是為什么它沒有 cursor 屬性的原因。
通常,我建議您檢查連接是如何建立的。 這是連接和查詢對象的基本示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.