【问题标题】:Multiple insert statements failing postgresql / psycopg2多个插入语句失败 postgresql / psycopg2
【发布时间】:2013-05-08 15:12:13
【问题描述】:

我正在使用 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 循环有什么关系吗?数据竞赛?

【问题讨论】:

    标签: python sql postgresql psycopg2


    【解决方案1】:
    for s, c in zip(date_list, count_list):
        self.cursor.execute(
            'INSERT INTO ufo_info(date, count) VALUES (%s, %s);'
            , (s, c)
        )
    

    【讨论】:

    • 非常顺利,比你先生!
    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2021-12-07
    • 2011-05-06
    相关资源
    最近更新 更多