2010-09-29 147 views
16

我在Python中使用psycopg2將一些值傳遞給postgres字符字段。一些字符串值包含句號,斜線,報價等psycopg2相當於mysqldb.escape_string?

用MySQL,我只是逃避與

MySQLdb.escape_string(my_string) 

字符串是否有psycopg2等效?

回答

2

Psycopg2沒有這樣的方法。它有一個extension用於將Python值修改爲ISQLQuote對象,並且這些對象有一個getquoted()方法來返回與PostgreSQL兼容的值。

見本博客,瞭解如何使用它的一個例子: Quoting bound values in SQL statements using psycopg2

+4

注意的傢伙有錯:他想要做什麼可以用'mogrify()'方法(HTTP獲得:// initd.org/psycopg/docs/cursor.html#cursor.mogrify) – piro 2010-10-06 10:15:55

+0

感謝@piro,看起來更容易,儘管它可能用於完整的SQL表達式或查詢,而不是j引用個別價值。 – 2010-10-06 15:42:22

+0

還要注意,同樣執行的mogrify不處理轉義表名稱,僅處理參數。 – a1an 2015-07-29 08:16:59

22

轉義是自動的,你只需要調用:

cursor.execute("query with params %s %s", ("param1", "pa'ram2")) 

(注意,蟒蛇%運營商使用)並且值將被正確地轉義。

可以手動逃生使用extensions.adapt(var)變量,但是這將是容易出錯,不能保持到帳戶的連接編碼:它是應該在定期的客戶端代碼中使用。

+1

與adapt()相同,您可以明確地使用特定的自適應協議對象;例如 'QuotedString(r「O'Reilly」)。getquoted()' 請參閱[文檔](http://initd.org/psycopg/docs/extensions.html#sql-adaptation-protocol-objects) – rakslice 2011-04-20 21:37:29

0

在該查詢參數是不夠萬一完整的SQL通過psycopg2逃脫的方法,你需要給自己逃避字符串,你可以使用Postgres escaped string constants與Python的repr(沿因爲Python的規則爲逃避非ASCII和Unicode字符是一樣的Postgres的):

def postgres_escape_string(s): 
    if not isinstance(s, basestring): 
     raise TypeError("%r must be a str or unicode" %(s,)) 
    escaped = repr(s) 
    if isinstance(s, unicode): 
     assert escaped[:1] == 'u' 
     escaped = escaped[1:] 
    if escaped[:1] == '"': 
     escaped = escaped.replace("'", "\\'") 
    elif escaped[:1] != "'": 
     raise AssertionError("unexpected repr: %s", escaped) 
    return "E'%s'" %(escaped[1:-1],)