[英]MYSQLdb/Python - not all arguments converted during string formatting error?
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: 尝试执行这样的SELECT时:
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)
);
That is because the second argument of execute is an iterable . 那是因为execute的第二个参数是可迭代的 。 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),))
您应该给元组,而不需要解析str;
db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (request.apikey,))
you are much better off with something like this: 像这样您会变得更好:
db.cursor.execute("SELECT password FROM USERS WHERE apikey = {0}".format(str(request.apikey))) db.cursor.execute(“从用户那里选择密码apikey = {0}”。format(str(request.apikey)))
given that request.apikey can be implicitly converted into a string 鉴于request.apikey可以隐式转换为字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.