修复Python Pg中的类型错误
感谢bobince帮忙解决第一个bug!
在下面的内容中,如何使用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 个回答
4
INSERT INTO files('binf','file_name') VALUES(file,file_name)
你把(...)
部分搞反了,你是想把列(file, filename)
的值插入到字符串('binf', 'file_name')
里。其实你并没有把变量binf
和file_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 }
)