Using Python quick insert many columns into Sqlite\Mysql

我与影子孤独终老i 提交于 2020-01-02 10:18:16

问题


If Newdata is list of x columns, How would get the number unique columns--number of members of first tuple. (Len is not important.) Change the number of "?" to match columns and insert using the statement below.

csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()

回答1:


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.

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)

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)

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

Finally,

csr.executemany(sql, Newdata)

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




回答2:


If you're looking for the maximum number of items in all elements in Newdata, it's simply:

num_columns = max(len(t) for t in Newdata)

This, of course, assumes python 2.5 or greater.

Not that I'm sure what you're attempting would work, but the insert statement would then become:

sql = "INSERT INTO test.data VALUES (%s)" % ",".join('?' * num_columns)



来源:https://stackoverflow.com/questions/3732490/using-python-quick-insert-many-columns-into-sqlite-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!