这段代码在数据库中只写了一行?

2024-04-25 23:56:08 发布

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

此代码只在DB中写入一行

我发现这个代码没有错误。在

但这为什么不插入第一行呢?在

def transremovechars():
    cur.execute('drop table transforms')
    char_cfg = config.get('Transform_Variables', 'Chars_to_be_removed')      #Reads all the special chars to be removed from specialchars.txt#
    cur.execute('select * from originallist')
    for row in cur:                                                         #Applies transformation to remove chars for each row in a loop#
        company = row[0]
        for specialchars in char_cfg:
            company =  company.replace(specialchars, '')
        cur.execute('Insert into transforms (Transresult1) values (\'' + company + '\')')
    con.commit() 

Tags: to代码inforexecutebecfgcompany
3条回答

在使用表之前,您似乎要删除表transforms。你确定要吗?或者你忘了展示再次创建它的代码吗?在

如果您只使用第一列,您的select *可能会过度使用。也许您想在SELECT中命名该字段。在

此外,您应该将插入行替换为

cur.execute('Insert into transforms (Transresult1) values (?)', company)

不过,迭代光标应该没问题。也许你可以在你的print循环中插入一些print语句。。。在

大意是您应该cur.fetchall()并对其进行迭代的注释可以正常工作。代码中真正的错误是,一旦使用cur插入,它就是一个“新事物”,原始生成器被重置(cur有next())方法。在

您可以使用cur而不必执行fetchall操作,只需创建第二个游标ins_cur = con.curson()并同时使用这两个游标。更多的高级效果可以通过迭代或使用在一个连接上打开的多个游标来实现。在

是的,请为您的dbapi模块使用正确的variable binding。在

您忘了cur.fetchall()

def transremovechars():
    cur.execute('drop table transforms')
    char_cfg = config.get('Transform_Variables', 'Chars_to_be_removed')      #Reads all the special chars to be removed from specialchars.txt#
    cur.execute('select * from originallist')
    for row in cur.fetchall():                                                         #Applies transformation to remove chars for each row in a loop#
        company = row[0]
        for specialchars in char_cfg:
            company =  company.replace(specialchars, '')
        cur.execute('Insert into transforms (Transresult1) values (\'' + company + '\')')
    con.commit() 

相关问题 更多 >