即使不满足条件,SQLite也会持久执行sql

时间:2019-06-30 05:07:50

标签: python python-3.x sqlite flask

即使len(cursor.fetchall())大于0,为什么此代码仍将用户添加到sqlite3 db?

#just for refrence, the issue is in the next block of code
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.route("/add_user", methods=['POST'])
def add_user():
    data = request.get_json(force=True)
    cursor = get_db().cursor()
    response = cursor.execute("SELECT * FROM users WHERE email = ?", (data['email'],))
    print('res_length', len(response.fetchall()))
    res_length = len(response.fetchall())

    if res_length > 0:
        return jsonify({"message": "User exists"})
    else: #This always executes!!! Why?????
        cursor.execute("INSERT INTO users (name, email, password) VALUES(?, ?, ?)", (data['name'], data['email'], data['password']))
        get_db().commit()
        get_db().close()
        return jsonify({
        "message": "New User added",
        "status": "ok",
        "status_code": 200
        })

使用Flask-1.0.3和Python-3.7.3

1 个答案:

答案 0 :(得分:0)

显然,您只能在光标响应上调用.fetchall()。进一步尝试在同一光标响应上调用.fetchall()将返回一个空列表。 删除打印语句:print('res_length', len(response.fetchall()))允许我使用res_length = len(response.fetchall())并解决了问题。

相关问题