我正在使用 scrapy 抓取一个网页,然后将其添加到 postgres 数据库中。 第一个 INSERT 语句工作正常,我可以从数据库中选择项目。第二个好像插入了数据但是所有字段都是空白
date | count
---------------------------+-------
04/2013 |
03/2013 |
02/2013 |
这是我的代码:
#Database init
self.conn = psycopg2.connect("dbname='dataproject' user='xxxx' host='localhost' password='xxxxxx'")
self.cursor = self.conn.cursor()
#CSV files
self.DatavisItemCsv = csv.writer(open('DatavisTable.csv', 'wb'))
self.DatavisItemCsv.writerow(['dates', 'counts'])
def process_item(self, item, spider):
self.DatavisItemCsv.writerow([item['dates'], item['counts']])
date_list = item['dates']
count_list = item['counts']
for s in date_list:
self.cursor.execute('INSERT INTO ufo_info(date) VALUES (%s);', [s])
for c in count_list:
self.cursor.execute('INSERT INTO ufo_info(count) VALUES (%s);', [c])
self.conn.commit()
这与我的 for 循环有什么关系吗?数据竞赛?
最佳答案
for s, c in zip(date_list, count_list):
self.cursor.execute(
'INSERT INTO ufo_info(date, count) VALUES (%s, %s);'
, (s, c)
)
关于python - 多个插入语句失败 postgresql/psycopg2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444251/