简体   繁体   中英

Why MySql connection not working on Flask Python API

I was using sqlite however moved to MySqL

Sqlite code that worked:

@app.route('/api/v1/users/user', methods=['GET'])
def api_filter():
    query_parameters = request.args
userid = query_parameters.get('userid')
username = query_parameters.get('username')

query = "SELECT * FROM tblUser WHERE"
to_filter = []

if userid:
    query += ' user_id=? AND'
    to_filter.append(userid)
if username:
    query += ' username=? AND'
    to_filter.append(username)
if not (userid or username):
    return page_not_found(404)

query = query[:-4] + ';'

conn = sqlite3.connect('dbApp.db')
conn.row_factory = dict_factory
cur = conn.cursor()

results = cur.execute(query, to_filter).fetchall()

return jsonify(results)

Now when I change it to MySQL it does not work:

@app.route('/api/v1/users/user', methods=['GET'])
def api_filter():
    query_parameters = request.args
userid = query_parameters.get('userid')
username = query_parameters.get('username')

query = "SELECT * FROM tblUser WHERE"
to_filter = []

if userid:
    query += ' user_id=? AND'
    to_filter.append(userid)
if username:
    query += ' username=? AND'
    to_filter.append(username)
if not (userid or username):
    return page_not_found(404)

query = query[:-4] + ';'

conn = mysql.connector.connect(host="localhost", user="root", password="green", database="dbApp")
conn.row_factory = dict_factory
cur = conn.cursor()

results = cur.execute(query, to_filter).fetchall()

return jsonify(results)

The error returned: results = cur.execute(query, to_filter).fetchall() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 260, in execute raise errors.ProgrammingError( mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement 127.0.0.1 - - [28/Dec/2020 17:47:11] "

This is after running: http://127.0.0.1:5000/api/v1/users/user?userid=3&username=Jo

http://127.0.0.1:5000/api/v1/users/user?userid=3

http://127.0.0.1:5000/api/v1/users/user?username=Jo

Also added this: from flask import request, jsonify import mysql.connector

Here is what the documentation says:

cursor.execute(operation, params=None, multi=False) This method executes the given database operation (query or command). The parameters found in the tuple or dictionary params are bound to the variables in the operation. Specify variables using %s or %(name)s parameter style (that is, using format or pyformat style). execute() returns an iterator if multi is True.

I think there are two problems with your code: you are using? for bind variables instead of %s, and you are passing in a list instead of a tuple. Alternatively use named parameters and pass in the values with a dict. Try both and see what you like most.

  1. user_id = %s" and to_filter = (userid, ) . You can use the list you have now and just convert it with tuple() .
  2. " user_id = %{user_id}" and set to_filter = {'user_id': userid } .

It is cleaner to build a list of conditions, then ' AND '.join(conditions) instead of removing the extra AND . You can simplify the code a little bit by just leaving out the ';'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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