2016-03-03 72 views
1

我有點好奇什麼是pythonic /最好的方式來解決我的問題。pymssql utf8:查詢反斜槓

一個簡短的代碼示例:

import pymssql 
conn = pymssql.connect("SERVER", 'sa', 'PASSWORD', 'DATABASE', charset='utf8') 

cursor = conn.cursor() 

sql = "SELECT 'foo\bar' as bs_field" 
cursor.execute(sql) 
row = cursor.fetchone() 
print row[0] 
# missing \, returns u'foobar' 

sql = "select FIELD_CONTAINING_BACKSLASH from TABLE" 
cursor.execute(sql) 
row = cursor.fetchone() 
print row[0] 
# all OK here 

sql = "SELECT 'foo\\bar' as bs_field" 
cursor.execute(sql) 
row = cursor.fetchone() 
print row[0] 
# this is OK too 

我想知道爲什麼\丟失在第一個例子 - 有沒有更好的解決方案,報價每一個SQL?

回答

1

我是個白癡!

與mssql無關,它只是python字符串。

r'bla\bla' 
'bla\\bla' 

參考:https://docs.python.org/2.0/ref/strings.html

+0

的確。請注意,在* some *數據庫中(例如,MySQL的默認設置和PostgreSQL的舊版本),反斜槓確實很特殊,您需要編寫'r'SELECT'foo \\ bar'「'或'」SELECT'foo \\\\吧'「'。這不是符合ANSI SQL標準的行爲,SQL Server也不這樣做,但混淆是使用參數化查詢而不是SQL字符串文字的另一個好理由。 – bobince

+0

的確,我大部分時間都在使用這些功能,但是如果您忘記了python的基礎知識,它並沒有幫助:-) –