感谢 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".
最佳答案
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
接口(interface)或其他非 PostgreSQL 特定的 DB-API 兼容接口(interface)之一。 DB-API 在 execute
方法中为您提供参数化:
cursor.execute(
'INSERT INTO files (file, file_name) VALUES (%(content)s, %(name)s)',
{'content': f.read(), 'name': f.name }
)
关于python - 修复 Python 的 Pg 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1770786/