繁体   English   中英

即使使用 connection.commit() 也无法将数据提交到数据库(使用 Python flask MySQL)

[英]Not able to Commit data to database (using Python flask MySQL) even after using connection.commit()

尽管在 Python 烧瓶中使用了 connection.commit(),但我的数据并未存储在 db 中。 这是我的代码:

from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)

def getMysqlConnection():

    mysql = MySQL()
    app.config['MYSQL_DATABASE_USER'] = "user_name"
    app.config['MYSQL_DATABASE_PASSWORD'] = "pass_string"
    app.config['MYSQL_DATABASE_DB'] = "db_name"
    app.config['MYSQL_DATABASE_HOST'] = "hostname"

    mysql.init_app(app)

    connection = mysql.connect()
    cursor = connection.cursor()
    return {"cursor":cursor,"connection":connection}

cursor = getMysqlConnection()['cursor']   #####global variables####
connection = getMysqlConnection()['connection']

def main_function():
    cursor.execute("Insert into table_name "
                       "(col1,col2,col3,col4) "
                       "Values (%s,%s,%s,%s,%s,%s)",
                       (val1,vla2,val3,val4)
                       )
    connection.commit()

这不是在数据库中保存代码,我不知道为什么。

会不会是下面的代码对数据库连接进行了两次初始化?

cursor = getMysqlConnection()['cursor']   #####global variables####
connection = getMysqlConnection()['connection']

尝试

db =  getMysqlConnection()
cursor = db['cursor']
connection = db['connection']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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