簡體   English   中英

修復Python的Pg中的類型錯誤

[英]Fixing a type-error in Python's Pg

感謝您在解決第一個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".

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接口或其他非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 }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM