在表中插入列表或元组而不迭代postgresq

2024-05-03 09:00:03 发布

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

我是python新手。我试图实现的是不经过迭代就将list/tuple中的值插入redshift表中。
下面是我用来创建列表/元组的代码。

cursor1.execute("select domain from url limit 5;")
for record, in cursor1:
    ext = tldextract.extract(record)
    mylist.append(ext.domain + '.' + ext.suffix)

mytuple = tuple(mylist)

我不知道什么是最好的使用,元组还是列表。print(mylist)和{}的输出如下。

List output
['friv.com', 'steep.tv', 'wordpress.com', 'fineartblogger.net', 'v56.org']
Tuple Output
('friv.com', 'steep.tv', 'wordpress.com', 'fineartblogger.net', 'v56.org')

现在,下面是我用来将值插入redshift表的代码,但是我得到了一个错误:

^{pr2}$

Error - not all arguments converted during string formatting

感谢任何帮助。如果需要任何其他详细信息,请告诉我,我将编辑我的问题。

更新1:


尝试使用下面的代码并得到不同的错误。在

args_str = ','.join(cur.mogrify("(%s)", x) for x in mylist)
cur.execute("INSERT INTO table VALUES " + args_str) 

ERROR - INSERT has more expressions than target columns


Tags: 代码incomredshift列表forexecutedomain
2条回答

我想你在找Fast Execution helpers

mylist=[('t1',), ('t2',)] 
execute_values(cursor2, "INSERT INTO sample(domain) %s", mylist, page_size=100)

它的作用是用100个值替换%s。我不知道你可以设置多高的页面大小,但这应该是更高的性能。在

终于找到了解决办法。由于某些原因,cur.mogrify没有给我正确的插入sql字符串。创建了我自己的SQl字符串,它比cur.executeall()

list_size = len(mylist)

for len in range(0,list_size):
    if ( len != list_size-1 ):
        sql = sql + ' ('+ "'"+  mylist[len] + "'"+ ') ,'
    else:
        sql = sql + '('+ "'"+  mylist[len] + "'"+ ')'

cursor1.execute("INSERT into sample(domain) values " + sql)

谢谢你们的帮助!在

相关问题 更多 >