简体   繁体   中英

Python - AttributeError: 'NoneType' object has no attribute 'cursor' python flask

I'm trying to populate the courses selectfield in my webapp using data from the database. this is my attempt.

this the form `

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

'

when I run the program i get this error

`

  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'

` I can't seem to figure out whats wrong..

edit:

This part works fine:

  def all(cls):
        cursor = mysql.connection.cursor()

        sql = "SELECT * from courses"
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

It fetches all the data from the database table. However, it doesn't work when selecting only one column. Please bear with me. I'm new to this kind of stuff.

To create a cursor, use the cursor() method of a connection object:

cnx = mysql.connector.connect(database='Hello_World')
cursor = cnx.cursor()

It seems like your mysql.connection object is None in that particular case. That's why it doesn't have a cursor attribute.

Generally, I recommend you to check how the connection has been established. Here is a basic example for the connection and query objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM