Executing database query gives "TypeError: not all arguments converted during string formatting"

10.1k views Asked by At

I'm trying to query my database with MySQLdb, but when I send a query with parameters I get TypeError: not all arguments converted during string formatting. I think it has something to do with the %s in the query. How do I fix this error?

Main.py:

from flask import Flask, request
from app.config import DB
from app.items.items import ItemsAPI

app = Flask(__name__)
db = DB()

app.register_blueprint(ItemsAPI)

@app.route('/home')
def hello_world():
    return "Welcome to Omnimoda."

@app.route('/dbtest', methods=['GET'])
def hello_database():
    q_sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'"
    a_sql = "omnimoda"
    test_request = db.query(q_sql, a_sql)
    result_request = test_request.fetchall()
    if (result_request is None):
        return "Database does not exist."
    else:
        return "Database exists."

Items.py:

from flask import Flask, request, jsonify, json, Blueprint
from app.config import DB

ItemsAPI = Blueprint('ItemsAPI', __name__)
db = DB()

@ItemsAPI.route('/items/listbycode', methods=['POST'])
def get_item_by_code():
    value = request.form['value']
    q_list_all = "SELECT * FROM item_info WHERE item_code = '%s'"
    print q_list_all
    a_list_all = (value)
    items_request = db.query(q_list_all, a_list_all)
    json_output = json.dumps(items_request.fetchall())
    return json_output

config.py:

from flask import Flask
import MySQLdb

class DB:
    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(host="localhost", user="user", passwd="passwd", db="test_dbase")
        self.conn.autocommit(True)

    def query(self, sql, values):
        try:
            print values
            cursor = self.conn.cursor()
            cursor.execute(sql)
        except (AttributeError, MySQLdb.OperationalError):
            self.connect()
            cursor = self.conn.cursor()
            cursor.execute(sql)
        return cursor

Traceback:

Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/lanceguinto/Documents/Project_Omnimoda/API/app/items/items.py", line 26, in get_item_by_code
    items_request = db.query(q_list_all, a_list_all)
  File "/Users/lanceguinto/Documents/Project_Omnimoda/API/app/config.py", line 15, in query
    cursor.execute(sql, values)
  File "build/bdist.macosx-10.10-intel/egg/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
2

There are 2 answers

2
Joran Beasley On BEST ANSWER

cursor.execute expects a list as its second argument

q_list_all = "SELECT * FROM item_info WHERE item_code = '%s'"
print q_list_all
a_list_all = (value,) #the comma makes it a list not the parens
items_request = db.query(q_list_all, a_list_all)

when you pass it a string

cur.execute(qry,"MyArg") # =becomes==> cur.execute(qry,["M","y","A","r","g"])

on a somewhat unrelated note you should really think about just using an ORM like sqlalchemy

1
Daniel Roseman On

(value) is not a tuple, it's just a string. And a string is an iterable of its characters. So in fact it's as if you're passing a list of the characters in the input field into the SQL statement, which only has room for one parameter.

Use (value,) instead.