Python“tuple”无法转换为MySQL类型

2024-06-28 10:52:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个程序中,我想做的是在操作数据后将其发送到数据库中发送的名为concurgaison_pré的specefic表中,但当我使用函数cursor.executemany()时<;代码中有mycursor.executemany()>;第二个参数就像不会传递一样,虽然它的格式是正确的(元组列表),但是当我放置另一个简单的元组列表而不是它传递的实际数据时, 我试图通过used type()方法查看其数据类型是否为true,但它给了我一个列表,下面是错误: raise errors.ProgrammingError( mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type _代码如下:

def conjugate_1er_gr_pré():

    mycursor.execute("SELECT nom FROM conjugaison_verbe WHERE groupe = 1")
    vrbs1gr = mycursor.fetchall()
    termi_1_gr = ['e', 'es', 'e', 'ons', 'ez', 'ent']
    
    res = np.array([])
    
    result = []
    for x in vrbs1gr:
        # converting the data type of vrbs1gr from tuple to string
        y = str(x)
        # Slicing from the beginning
        y = y[2:]
        # Slicing from the end
        global z
        z = y[:-3]
        for j in termi_1_gr:
            m = z.replace("er", j)
            result.append(m)
            arr = np.append(res, result)
    

    def slicer(n, iterable):
        args = [iter(iterable)] * n
        return zip(*args)
    arr1 = slicer(6, arr)

    return tuple(arr1)

sql = "INSERT INTO conjugaison_présent (je,tu,il,nous,vous,ils) VALUES(%s,%s,%s,%s,%s,%s);"
vals = conjugate_1er_gr_pré()
val = list(vals)
print(val)
mycursor.executemany(sql,val)
mydb.commit()

打印的“val”类似于:

[('joue', 'joues', 'joue', 'jouons', 'jouez', 'jouent'), ('passe', 'passes', 'passe', 'passons', 'passez', 'passent'), ('travaille', 'travailles', 'travaille', 'travaillons', 'travaillez', 'travaillent'), ('achete', 'achetes', 'achete', 'achetons', 'achetez', 'achetent')]

有什么建议吗


Tags: the数据代码from列表typevalpr
2条回答

试试这个:

尝试将您的函数更改为此

def conjugate_1er_gr_pré():

    mycursor.execute("SELECT nom FROM conjugaison_verbe WHERE groupe = 1")
    vrbs1gr = mycursor.fetchall()
    termi_1_gr = ['e', 'es', 'e', 'ons', 'ez', 'ent']

    res = []

    for verb in vrbs1gr:

        # The first element of the tuple is the verb, which is probably the only element based on your select
        verb = verb[0]

        # now we can create the replace with a tuple creation with list comprehension
        conj = tuple(verb.replace(er, termination) for termination in termi_1_gr)

        res.append(conj)

    return res
sql = "INSERT INTO conjugaison_présent (je, tu, il, nous, vous, ils) VALUES (%s, %s, %s, %s, %s, %s);"
vals = conjugate_1er_gr_pré()
print(vals)
mycursor.executemany(sql, vals)
mydb.commit()

这将返回一个包含6个元素的元组列表,这是ExecuteMy所期望的。请注意您的查询,在值后面缺少一个空格

您可以尝试在元组列表中循环:

sql = "INSERT INTO conjugaison_présent (je,tu,il,nous,vous,ils) 
VALUES(%s,%s,%s,%s,%s,%s);"
vals = conjugate_1er_gr_pré()
val = list(vals)
print(val)
for x in val:
    mycursor.executemany(sql,x)
    mydb.commit()

相关问题 更多 >