0

Trying to select some info from a database, I have a database manager class that looks like this:

class DatabaseManager:
    def __init__(self):
        self.connection = MySQLdb.connect(host="localhost", 
                     user="neal", 
                      passwd="hacker123",
                      db="massive") 

        self.cursor = self.connection.cursor()

When trying to do a SELECT like this:

    db = DatabaseManager()
    db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", str(request.apikey))

I get a

TypeError: not all arguments converted during string formatting

This is odd as I have similar queries elsewhere that worked fine, like this one:

db.cursor.execute('''INSERT into USERS(email, username, password, apikey) values (%s, %s, %s, %s)''',
    (request.email, request.username, request.password, apikey))

Am I doing this wrong?

EDIT: Column confusion, table looks like this:

CREATE TABLE users (
id int NOT NULL AUTO_INCREMENT, 
email varchar(255) NOT NULL,
username varchar(25) NOT NULL,
password varchar(25) NOT NULL,
apikey varchar(45) NOT NULL,
PRIMARY KEY (id),
UNIQUE(email),
UNIQUE(username),
UNIQUE(apikey)
);
1
  • Did you try passing the argument as a tu9le with a single string? Commented Nov 4, 2014 at 19:20

3 Answers 3

1

That is because the second argument of execute is an iterable. So you would be better off with a list, set, or tuple.

Try this:

db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (str(request.apikey),))
Sign up to request clarification or add additional context in comments.

Comments

1

You should give tuple, no need to parse str;

db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (request.apikey,))

Comments

-1

you are much better off with something like this:

db.cursor.execute("SELECT password FROM USERS WHERE apikey = {0}".format(str(request.apikey)))

given that request.apikey can be implicitly converted into a string

2 Comments

When I do this, I get this error: File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler OperationalError: (1054, "Unknown column 'a443160d' in 'where clause'"). The API key is in the format a443160d-66fb-482c-953b-af1349b9c5ba, and the column is named apikey. Why does it think the value I'm passing it is the name of the column?
if apikey value is a string, then include quotations('). If its a integer it should be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.