Python MySQLdb TypeError:并非所有参数都在字符串格式化期间转换 [英] Python MySQLdb TypeError: not all arguments converted during string formatting

查看:54
本文介绍了Python MySQLdb TypeError:并非所有参数都在字符串格式化期间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此脚本后:

#! /usr/bin/env python
import MySQLdb as mdb
import sys    

class Test:
    def check(self, search):
        try:
            con = mdb.connect('localhost', 'root', 'password', 'recordsdb');

            cur = con.cursor()
            cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )

            ver = cur.fetchone()

            print "Output : %s " % ver

        except mdb.Error, e:

            print "Error %d: %s" % (e.args[0],e.args[1])
            sys.exit(1)

        finally:    
            if con:    
                con.close()

test = Test()
test.check("test")

我收到以下错误:

./lookup 
Traceback (most recent call last):
  File "./lookup", line 27, in <module>
    test.check("test")
  File "./lookup", line 11, in creep
    cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
  File "/usr/local/lib/python2.7/dist-packages/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

我不知道为什么.我正在尝试进行参数化查询,但这只是一种痛苦.我对 Python 有点陌生,所以这可能是一个明显的问题.

I have zero idea why. I'm trying to do parameterized querys, but it's been nothing but a pain. I'm somewhat new to Python, so it's probably an obvious problem.

推荐答案

代替这个:

cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )

试试这个:

cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )

请参阅 MySQLdb 文档.理由是 execute 的第二个参数表示要转换的对象列表,因为在参数化查询中可以有任意数量的对象.在这种情况下,您只有一个,但它仍然需要是可迭代的(元组而不是列表也可以).

See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).

这篇关于Python MySQLdb TypeError:并非所有参数都在字符串格式化期间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆