尝试从数据库中选择一些信息,我有一个如下所示的数据库管理器类:
class DatabaseManager:
def __init__(self):
self.connection = MySQLdb.connect(host="localhost",
user="neal",
passwd="hacker123",
db="massive")
self.cursor = self.connection.cursor()
当尝试像这样做SELECT时:
db = DatabaseManager()
db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", str(request.apikey))
我得到了
TypeError: not all arguments converted during string formatting
这很奇怪,因为我在其他地方有类似的查询工作正常,如下:
db.cursor.execute('''INSERT into USERS(email, username, password, apikey) values (%s, %s, %s, %s)''',
(request.email, request.username, request.password, apikey))
我这样做错了吗?
编辑:列混淆,表格如下:
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)
);
答案 0 :(得分:1)
那是因为second argument of execute is an iterable。所以你最好使用列表,设置或元组。
试试这个:
db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (str(request.apikey),))
答案 1 :(得分:1)
你应该给元组,不需要解析str;
db.cursor.execute("SELECT password FROM USERS WHERE apikey = %s", (request.apikey,))
答案 2 :(得分:-1)
你这样做会好得多:
db.cursor.execute(" SELECT密码FROM USERS WHERE apikey = {0}" .format(str(request.apikey)))
鉴于request.apikey可以隐式转换为字符串