本文介绍了使用Flask调用connection.commit()后,MySQL不更新(WORKING)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用flask来构建一个简单的web应用程序,但无论出于什么原因,conn.commit()都没有将数据提交到数据库中。我知道这一点,因为当我手动添加一些东西到数据库中的数据不会改变,但ID部分每增加一次我测试它(因为它使用自动增量)。所以基本上我的当前表有ID 1,用户名测试,密码测试和手动插入的下一个条目(在尝试使用我的应用程序之后)是ID 5,用户名密码,密码等等。编辑:我不得不改变cursor = mysql.connect()。cursor()到conn.cursor() )

  @ app.route('/ add_data /')
def add_tv_to_database():
conn = mysql.connect()
cursor = mysql.connect()。cursor()
cursor.execute(INSERT INTO _accounts VALUES(null,'test','test'))
conn.commit()
return render_template('index.html')


解决在第四行代码中,将它从 cursor = mysql.connect()。cursor()更改为 cursor = conn.cursor()。这将确保游标使用现有的数据库连接(来自上一行代码),而不是创建新的MySQL连接。


I'm using flask to build a simple web app but for whatever reason the conn.commit() is not committing the data into the database. I know this because when I manually add something to the database the data doesn't change but the ID section increases each time I test it (because its using auto increment). So basically my current table has ID 1, Username test, Password test and the next entry that I inserted manually (after trying to use my application) was ID 5, Username blah, Password blah. Is there any specific reason that the commit isn't working?

EDIT: I had to change cursor = mysql.connect().cursor() to conn.cursor()

@app.route('/add_data/')
def add_tv_to_database():
    conn = mysql.connect()
    cursor = mysql.connect().cursor()
    cursor.execute("INSERT INTO _accounts VALUES (null, 'test','test')")
    conn.commit()
    return render_template('index.html')
解决方案

In the fourth line of your code, change it from cursor = mysql.connect().cursor() to cursor = conn.cursor(). This will ensure that the cursor uses the existing connection to database (from the previous line of code), instead of creating a new MySQL connection.

这篇关于使用Flask调用connection.commit()后,MySQL不更新(WORKING)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:56