_mysql_exceptions.OperationalError:(1271,"操作中的非法混合操作' IN'")在python中

时间:2017-06-03 07:21:14

标签: python mysql

我在python中有一个MYSQL查询。它工作正常。但是,在删除表中的某个元组后,会出现以下错误。

_mysql_exceptions.OperationalError: (1271, "Illegal mix of collations for operation ' IN '")

以下是我的代码。

with open('out.csv', 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
    text=(row['text'])
    emotion = (row['emotion'])
    my_list = (text, emotion)
    my_array = np.asarray(my_list)
    sentence = (text.lower())
    w_tokenize = (word_tokenize(sentence))

    negation_words = [w for i, w in enumerate(w_tokenize) if i and (
        w_tokenize[i - 1] in ["not", "never", "no", "nobody", "nothing", "neither", "doesn't", "isn't", "wasn't",
                        "shouldn't", "wouldn't", "couldn't", "won't", "can't", "don't", "didn't"])]

    if w_tokenize== []:
        Value = ''
    else:
        cursor = conn.cursor()
        format_strings = ','.join(['%s'] * len(w_tokenize))
        cursor.execute("SELECT emotion_type FROM emotion WHERE key_word IN  (%s)" % format_strings,
                       tuple(w_tokenize))
        results = [res[0] for res in cursor.fetchall()]
        if results:
            frequencies = Counter(results)
            Value = max(frequencies, key=frequencies.get)
        else:
            Value = ''

但我无法找到解决方案。任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

首先,你以错误的方式呼叫execute。您通过字符串格式传递参数。这非常危险(让您对SQL注入开放)并且还会导致意外结果。正确的方法是

cursor.execute("SELECT emotion_type FROM emotion WHERE key_word IN  (%s)" , tuple(w_tokenize))

我认为您可能希望作为参数传递的是",".join(w_tokenize)

cursor.execute("SELECT emotion_type FROM emotion WHERE key_word IN  (%s)" , ",".join(w_tokenize))

因为IN子句内部的内容应该是子查询或逗号分隔的字符串。 mysql连接器不会自动将您的元组转换为CSV