【问题标题】:Can't write to MySQL DB无法写入 MySQL 数据库
【发布时间】:2015-12-15 17:04:57
【问题描述】:

我是一个尝试创建简单应用的 Flask 新手。我目前卡在用户注册中,我试图将数据保存在数据库中,但没有发生。但是,我正在做的日志记录表明该操作是成功的。谁能告诉我我做错了什么?

这里有一些代码可以帮助你理解我想要做什么:

from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from flask.ext.mysqldb import MySQL

# Configuration
MYSQL_HOST     = 'localhost'
MYSQL_USER     = 'root'
MYSQL_PASSWORD = 'root'
MYSQL_DB       = 'up2date'
DEBUG          = True
SECRET_KEY     = 

'\xc6)\x0f\\\xc5\x86*\xd7[\x92\x89[\x95\xcfD\xfd\xc1\x18\x8e\xf1P\xf7_\r'

# Create the flask app
app = Flask(__name__)
app.config.from_object(__name__)
# Create instance for working with MySQL
mysql = MySQL(app)

# Function to connect to DB
def connect_db():
    return mysql.connection.cursor()

# define functions that will make DB available automatically on each request
@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    g.db.close()

最后,执行用户注册的代码:

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        result = g.db.execute('INSERT INTO users (email, password) VALUES (%s, %s)', [email, password])
        print(email, password)
        print(result, " rows affected")
        flash('Registration successful! You may log in now.')
        return redirect(url_for('show_home'))

print这两条语句确认邮件地址和密码被正确捕获,result变量包含1,表示有1行受到影响。但是数据库中仍然没有行。我之前认为这与提交有关,但g.db.commit() 抛出错误:AttributeError: 'Cursor' object has no attribute 'commit'

【问题讨论】:

  • 能否提供commit的错误。
  • @ipinak 添加到我的帖子末尾!

标签: python-3.x flask


【解决方案1】:

我假设你使用 MySQL-python

connect_db() 返回游标而不是连接。正如异常所说,游标没有commit() 函数,但是连接具有您需要的提交函数。我认为你需要这样做:

def connect_db():
   return mysql.connection

有关更多信息,您可以查看code

【讨论】:

  • 我很遗憾没有提到图书馆。我实际上正在使用flask-mysqldb。我已将导入语句添加到代码的顶部。
  • Flask-MySQL 使用 MySQL-python,所以没关系。我的建议有效吗?
  • 好吧,好吧!非常感谢!它终于奏效了。 :D 我只需要更改我的代码以确保在g.db.cursor() 上调用execute() 并且您的建议有效。非常感谢你帮助我。 :-)
猜你喜欢
  • 2022-11-23
  • 2017-11-13
  • 2020-08-03
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 1970-01-01
相关资源
最近更新 更多