修复Python的Pg中的类型错误

时间:2009-11-20 14:29:54

标签: python postgresql types

感谢bobince解决第一个错误!

如何在以下内容中使用 pg.escape_bytea pg.escape_string

#1同时使用pg.escape_string和pg.escape_bytea

    con1.query(
            "INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
            (pg.escape_bytea(pg.espace_string(f.read())), pg.espace_string(pg.escape_bytea(f.name)))

我收到错误

AttributeError: 'module' object has no attribute 'espace_string'

我也以相反的顺序测试了两个转义失败。

#2没有pg.escape_string()

 con1.query(
                "INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
                (pg.escape_bytea(f.read()), pg.escape_bytea(f.name))
        )

我得到了

WARNING:  nonstandard use of \\ in a string literal
LINE 1: INSERT INTO files (file, file_name) VALUES ('%PDF-1.4\\012%\...
                                                    ^
HINT:  Use the escape string syntax for backslashes, e.g., E'\\'.
------------------------
-- Putting pdf files in 

我收到以下错误

#3只有pg.escape_string

------------------------
-- Putting pdf files in
------------------------
Traceback (most recent call last):
  File "<stdin>", line 30, in <module>
  File "<stdin>", line 27, in put_pdf_files_in
  File "/usr/lib/python2.6/dist-packages/pg.py", line 313, in query
    return self.db.query(qstr)
pg.ProgrammingError: ERROR:  invalid byte sequence for encoding "UTF8": 0xc7ec
HINT:  This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".

1 个答案:

答案 0 :(得分:4)

  

INSERT INTO文件('binf','file_name')VALUES(file,file_name)

您的(...)部分的轮次错误,您试图将列(file, filename)插入字符串文字('binf', 'file_name')。您实际上也没有将变量binffile_name的内容插入到查询中。

pg模块的query调用不支持参数化。你必须自己制作字符串:

con1.query(
    "INSERT INTO files (file, file_name) VALUES ('%s', '%s')" %
    (pg.escape_string(f.read()), pg.escape_string(f.name))
)

这假设f是文件对象;我不确定上面代码中file的来源或.read(binf)应该是什么意思。如果您使用bytea列来保存文件数据,则必须使用escape_bytea代替escape_string

优于创建自己的查询,让pg使用insert方法为您执行此操作:

con1.insert('files', file= f.read(), file_name= f.name)

或者,如果您想考虑在不同的数据库上运行应用程序,请考虑使用pgdb接口或其他不符合PostgreSQL的其他符合DB-API的接口。 DB-API为您提供execute方法的参数化:

cursor.execute(
    'INSERT INTO files (file, file_name) VALUES (%(content)s, %(name)s)', 
    {'content': f.read(), 'name': f.name }
)