Python游标返回行数而不是行数

时间:2013-09-12 21:26:30

标签: python mysql python-2.7 sql-like

编写脚本来清理一些数据。超级未经优化,但这个光标是 返回类似查询中的结果数而不是行我做错了什么。

#!/usr/bin/python
import re
import MySQLdb
import collections

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="admin", # your username
                      passwd="", # your password
                      db="test") # name of the data base

# you must create a Cursor object. It will let
#  you execute all the query you need
cur = db.cursor() 

# Use all the SQL you like
cur.execute("SELECT * FROM vendor")

seen = []

# print all the first cell of all the rows
for row in cur.fetchall() :
    for word in row[1].split(' '):
        seen.append(word)

_digits = re.compile('\d')
def contains_digits(d):
    return bool(_digits.search(d))


count_word = collections.Counter(seen)
found_multi = [i for i in count_word if count_word[i] > 1 and not contains_digits(i) and len(i) > 1]

unique_multiples = list(found_multi)

groups = dict()

for word in unique_multiples:
    like_str = '%' + word + '%'
    res = cur.execute("""SELECT * FROM vendor where name like %s""", like_str)

1 个答案:

答案 0 :(得分:2)

您正在存储cur.execute()的结果,即行数。你永远不会真正获取任何结果。

使用.fetchall()获取所有结果行或在执行后迭代光标:

for word in unique_multiples:
    like_str = '%' + word + '%'
    cur.execute("""SELECT * FROM vendor where name like %s""", like_str)
    for row in cur:
        print row