'NoneType'对象没有属性'cursor'

时间:2018-10-12 12:54:49

标签: mysql flask mysql-python

我使用Flask创建了一个非常简单的Web应用程序,并且连接了MySQL数据库。仅供参考,我在Windows上使用bash。

下面的函数将一个人注册到Mysql数据库中,并且可以正常工作。定义了游标对象,并将数据保存到MySQL中。

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule
    ],
    declarations: [
        AppComponent
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

当我想从mysql加载数据时,问题开始了:

@app.route('/register', methods=['GET','POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        name = form.name.data
        email = form.email.data
        username = form.username.data
        password = hash.encrypt(str(form.password.data))

        # Create cursor
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)",
        [name, email, username, password])

        # commit to db
        mysql.connection.commit()

        # close connection
        cur.close()

        flash('You are now registered and can log in', 'success')

        return redirect(url_for('login'))

    return render_template('register.html', form=form)

我得到了错误:

  

文件“ app.py”,第23行,在数据中       cur = mysql.connection.cursor()   AttributeError:'NoneType'对象没有属性'cursor'

@Martijn Pieters指出,这意味着我无法连接到mysql数据库。问题是,为什么烧瓶连接第一功能时没有问题,而第二功能有问题?

下面是我要复制的导入内容:

def data():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users")
    mysql.connection.commit()
    cur.close()

data()

2 个答案:

答案 0 :(得分:2)

发生错误是因为mysql.connectionNone。这里的对象mysql是什么类型都没关系。

Flask-MySQL documentation for MySQL.connection会告诉您该属性何时为None

  

尝试连接到MySQL服务器。

     

返回:绑定的MySQL连接对象(如果成功)或None(如果失败)。

因此连接服务器的尝试可能失败。该扩展将为每个请求打开一次与MySQL的连接;它无法成功连接到另一个请求。

查看source code for the extension时,我发现它在没有应用上下文时也会返回None(此时_app_ctx_stack.topNone。在请求之外使用此功能。

如果在请求之外确实需要此功能,则需要先manually create an app context

with app.app_context():
    cur = mysql.connection.cursor()

答案 1 :(得分:0)

当您的数据库连接未建立时会发生这些错误。所以请检查您的数据库连接方法和属性,然后尝试执行。

相关问题