【问题标题】:What is the correct way to Insert an image into Postgres with python?使用python将图像插入Postgres的正确方法是什么?
【发布时间】:2014-02-17 11:10:35
【问题描述】:

我试图改编herehere的例子

import psycopg2
#Given media_id and image_url and conn object
image_data = urllib2.urlopen(image_url).read()
sql =("INSERT INTO images (media_id, data) 
SELECT %s
WHERE 
NOT EXISTS (SELECT media_id FROM images WHERE media_is = CAST(%s as TEXT) ")
data_insert_image = (media_id, psycopg2.Binary(image_data))
cursor.execute(sql_insert_image, data_insert_image)
conn.commit()

结果是:

TypeError: not all arguments converted during string formatting

这对我来说很有意义,因为图像不是String;但是,我不知道如何正确插入。应该如何插入?

【问题讨论】:

  • 您的查询中有两条 SQL 语句。我会把它们一分为二。插入语句应该可以正常使用psycopg2.Binary
  • @nathancahill 将其分成两个查询并不能解决图像插入上的类型错误
  • 你在那里做了一个不正确的 upsert - 它在并发的情况下不起作用。我不清楚为什么 Psycopg2 不喜欢这个查询。 psycopg2.Binary(image_data)确实是处理bytea数据的正确方法。您的询问也是无稽之谈; INSERT 接受 (media_id, data) 但您只在 SELECT-list 中为 media_id 提供了一个参数。
  • 请说明当您尝试进行简单插入时会发生什么(因为这是关于二进制处理);保持 upsert 的混乱以备后用。关于 upserts,请阅读stackoverflow.com/questions/17267417/…

标签: python sql postgresql psycopg2


【解决方案1】:

您经过大量编辑的代码有很多问题,其中一些已经在 cmets 中指出。我希望这个例子相当清楚

import psycopg2, urllib2

image_url = 'http://example.com/theimage.jpg'
image_data = urllib2.urlopen(image_url).read()
media_id = 3

# triple quotes allows better string formating
sql = """
    with s as (
        select media_id 
        from images 
        where media_id = %(media_id)s
    )
    insert into images (media_id, data)
    select %(media_id)s, %(data)s
    where not exists (select 1 from s)
    returning media_id
;"""

# a parameter dictionary is clearer than a tuple
data_insert_image = {
    'media_id': media_id,
    'data': psycopg2.Binary(image_data)
}

conn = psycopg2.connect("host=localhost4 port=5432 dbname=db user=u password=p")
cursor = conn.cursor()
cursor.execute(sql, data_insert_image)
# fetchone returns a single tuple or null
result = cursor.fetchone()
conn.commit()

if result is not None:
    print 'Media Id {0} was inserted'.format(result[0])
else:
    print 'Media Id {0} already exists'.format(media_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-22
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多