mysql数据库没有更新成功_为什么我的mysql数据库没有更新(使用flask / python)

我正在尝试在用户输入用户名和密码时将用户添加到数据库中.但是,数据库根本没有更新,数据库中的所有信息都保持不变.我已经测试了代码并且它确实运行但是mysql.connect().commit()没有将代码提交到数据库.

我的烧瓶文件:

from flask import Flask, jsonify, render_template, request, Response, json, redirect, url_for

from flaskext.mysql import MySQL

import re

from MyFunction import *

from get_tv_name import *

mysql = MySQL()

app = Flask(__name__, static_folder="", static_url_path='')

app.config['SECRET_KEY'] = 'F34TF$($e34D';

app.config['MYSQL_DATABASE_USER'] = 'root'

app.config['MYSQL_DATABASE_PASSWORD'] = ""

app.config['MYSQL_DATABASE_DB'] = 'accounts'

app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

@app.route('/')

def index():

return render_template('index.html')

@app.route('/register.html/', methods=['GET', 'POST'])

def register():

error = None

if request.method == 'POST':

cursor = mysql.connect().cursor()

cursor.execute("SELECT * from _accounts where Username='" + request.form['username'] + "' and Password='" + request.form['password'] + "'")

data = cursor.fetchone()

if data == None:

cursor.execute("INSERT INTO _accounts VALUES (null, '" + request.form['username'] + "', '" + request.form['password'] + "')")

mysql.connect().commit

redirect(url_for('index'))

else:

error = "it is complete"

return render_template('/register.html/', error=error)

if __name__ == '__main__':

app.run(port=8080, debug=True)

我的HTML:

Create an Account!

First Name

Last Name

Username

Password

Create account

解决方法:

数据库未更新的原因是您没有提交事务.您使用mysql.conn()创建连接,然后通过添加.cursor()从中获取游标.当您提交更改时,再次调用mysql.conn()可以获得全新的连接.

您要做的是捕获对连接的引用,以便以后使用它.您还需要使用参数化查询来避免SQL注入攻击等问题.

conn = mysql.connect()

cursor = conn.cursor()

data = cursor.fetchone()

if data is None:

cursor.execute("INSERT INTO _accounts VALUES (null, %s, %s)", (request.form['username'], request.form['password']))

conn.commit()

redirect(url_for('index')) # I'm guessing you want to put a return here.

else:

error = "it is complete" # snip

最后,当与None比较时,你会想要使用is运算符而不是相等. From PEP8

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

标签:python,mysql,flask

来源: https://codeday.me/bug/20190728/1560744.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值