修复Python Pg中的类型错误

0 投票
1 回答
866 浏览
提问于 2025-04-15 16:12

感谢bobince帮忙解决第一个bug!

在下面的内容中,如何使用pg.escape_byteapg.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 个回答

4

INSERT INTO files('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接口或者其他符合DB-API的接口,这些接口不局限于PostgreSQL。DB-API在execute方法中提供了参数化的功能:

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

撰写回答