使用Python快速插入许多列到Sqlite\Mysql中
如果 Newdata 是 x 列的列表,如何获取唯一列数——第一个元组的成员数。 (Len 并不重要。)更改“?”的数量。匹配列并使用下面的语句插入。
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过“Newdata 是 x 列的列表”,我想您的意思是
x
元组,从那时起您继续谈论“第一个元组”。如果Newdata
是元组列表,则y = len(Newdata[0])
是这些元组中第一个元组中的项目数。假设这是您想要的数字(并且所有元组最好具有相同数量的项目,否则
executemany
将会失败!),@Nathan 的答案中的总体思路是正确的:使用适当数量的逗号分隔问号构建字符串:然后将其插入 SQL 语句的其余部分。 @Nathan 的插入方式适用于大多数 Python 2.any 版本,但如果您有 2.6 或更高版本,
则目前是首选(它也适用于 Python 3.any)。
最后,
会做自己想做的事。完成后请记住提交交易!-)
By "Newdata is list of x columns", I imagine you mean
x
tuples, since then you continue to speak of "the first tuple". IfNewdata
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: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,
is currently preferred (it also works in Python 3.any).
Finally,
will do what you desire. Remember to commit the transaction once you're done!-)
如果您正在寻找 Newdata 中所有元素的最大项目数,那么很简单:
当然,假设 python 2.5 或更高版本。
并不是说我确定您尝试的操作会起作用,但插入语句将变为:
sql = "INSERT INTO test.data VALUES (%s)" % ",".join('?' * num_columns)
If you're looking for the maximum number of items in all elements in
Newdata
, it's simply: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)