Reputation: 1056
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)
);
Upvotes: 0
Views: 2224
Reputation: 93
You should give tuple, no need to parse str;
db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (request.apikey,))
Upvotes: 1
Reputation: 111
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
Upvotes: -1
Reputation: 82028
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),))
Upvotes: 1