查看: 1714|回复: 3

Python MySQLdb TypeError: not all parameters are converted during string form...

[复制链接]

9

主题

74

帖子

185

积分

注册会员

Rank: 2

积分
185
发表于 2018-9-18 17:58:18 | 显示全部楼层 |阅读模式
运行此脚本时:
  1. #! /usr/bin/env python
  2. import MySQLdb as mdb
  3. import sys   

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

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

  10.             ver = cur.fetchone()

  11.             print "Output : %s " % ver

  12.         except mdb.Error, e:

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

  15.         finally:   
  16.             if con:   
  17.                 con.close()

  18. test = Test()
  19. test.check("test")
复制代码

我得到一个错误:
  1. ./lookup
  2. Traceback (most recent call last):
  3.   File "./lookup", line 27, in <module>
  4.     test.check("test")
  5.   File "./lookup", line 11, in creep
  6.     cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
  7.   File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
  8.     query = query % tuple([db.literal(item) for item in args])
  9. TypeError: not all arguments converted during string formatting
复制代码

我不明白为什么。
回复

使用道具 举报

11

主题

63

帖子

159

积分

注册会员

Rank: 2

积分
159
发表于 2018-9-18 17:59:43 | 显示全部楼层

cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
换成
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
请参阅MySQLdb 文档。原因是execute第二个参数表示要转换的对象列表,因为在参数化查询中可以有任意数量的对象。在这种情况下,你只有一个,但它仍然需要是一个可迭代的(一个元组而不是一个列表也可以)。
回复

使用道具 举报

10

主题

82

帖子

200

积分

中级会员

Rank: 3Rank: 3

积分
200
发表于 2018-9-18 18:00:31 | 显示全部楼层
你可以试试这段代码:
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", (search,) )
你可以参考文档
回复

使用道具 举报

11

主题

80

帖子

199

积分

注册会员

Rank: 2

积分
199
发表于 2018-9-18 18:01:47 | 显示全部楼层
'%'关键字非常危险,因为它是“SQL注入攻击”的主要原因。
所以你只需使用这段代码。
  1. cursor.execute("select * from table where example=%s", (example,))
复制代码

要么
  1. t = (example,)
  2. cursor.execute("select * from table where example=%s", t)
复制代码

如果你想尝试插入表格,试试这个。
  1. name = 'ksg'
  2. age = 19
  3. sex = 'male'
  4. t  = (name, age, sex)
  5. cursor.execute("insert into table values(%s,%d,%s)", t)
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表