且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python快速将许多列插入Sqlite \ Mysql

更新时间:2023-11-30 22:45:10

通过"Newdata是x列的列表",我想您的意思是x 元组,从那时起您一直在谈论第一个元组".如果Newdata是元组列表,则y = len(Newdata[0])是这些元组中第一个元组的项数.

By "Newdata is list of x columns", I imagine you mean x tuples, since then you continue to speak of "the first tuple". If Newdata is a list of tuples, y = len(Newdata[0]) is the number of items in the first one of those tuples.

假设这是您想要的数字(所有元组***具有相同的项目数,否则executemany 失败!),@ Nathan答案中的一般想法是正确的:构建带有适当数量的逗号分隔的问号的字符串:

Assuming that's the number you want (and all tuples had better have the same number of items, otherwise executemany will fail!), the general idea in @Nathan's answer is right: build the string with the appropriate number of comma-separated question marks:

holders = ','.join('?' * y)

然后将其插入到SQL语句的其余部分中. @Nathan的插入方式适用于大多数Python 2.any版本,但是,如果您有2.6或更高版本,

then insert it in the rest of the SQL statement. @Nathan's way to insert is right for most Python 2.any versions, but if you have 2.6 or better,

sql = 'INSERT INTO testdata VALUES({0})'.format(holders)

当前是首选(它也可以在Python 3.any中使用.)

is currently preferred (it also works in Python 3.any).

最后,

csr.executemany(sql, Newdata)

将做您想要的.完成后,请记住要提交事务!-)

will do what you desire. Remember to commit the transaction once you're done!-)