python - 多个插入语句失败 postgresql/psycopg2

标签 python sql postgresql psycopg2

我正在使用 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/

相关文章:

python - 如何跟踪使用 CPU 与 GPU 进行深度学习的时间?

SQL 查询用 Sum() 加入两个查询

java - 如何查询postgres数据库以获取特定坐标10公里半径内的所有点

postgresql - 调用没有其他函数权限的函数

ruby-on-rails - 导入 psql 文件 trows "ERROR: role "userabc“不存在”

python - 流式 pyspark 应用程序中的连接池

python - 尝试使用 pyomo 和 bonmin 求解模型。模型未正确传递给求解器

sql - 在单列上 : Algebraic operation on Aggregate functions

python - 从单个字符串中分离两个日期时间值

php - 预订系统-可用表