Python處理mysql特殊字符的問(wèn)題
有的時(shí)候我們會(huì)去掃表,然后拿出掃的結(jié)果再到另一張表里去查信息。比如下面一段
index_sql_str = 'select %s from user where %s = %d' % ('social_id', 'user_id', u_id) db_cursor.execute(index_sql_str) rows = [’'’ + row[0] + ’'’ for row in db_cursor.fetchall()] if len(rows) == 0: return None result = [] sql_str = 'select %s user_detail where %s in (%s)' % (','.join(user_third_column_name), 'social_id', ','.join(rows)) db_cursor.execute(sql_str)
常會(huì)有用%s或者+拼接query string的情況,這時(shí)候如果拿出來(lái)的鍵值帶有’或’’就會(huì)導(dǎo)致拼接出現(xiàn)問(wèn)題。
可以考慮用format,即
>>> a = ’test'test’>>> 'insert into user {0}'.format(a)’insert into user test'test’>>> b = 'test’test'>>> 'insert into user {0} where {1} = x'.format(a,b)’insert into user test'test where test’test = x’
如果大小寫都包含會(huì)自己增加轉(zhuǎn)義字符
補(bǔ)充拓展:基于python中寫mysql關(guān)于like % 的問(wèn)題
#@ 1 - 正常執(zhí)行的mysql 語(yǔ)句為: select * from RESIDENTIAL_AREA where RA_ID like ’HF-%’ #@ 2 - 在python 代碼中為: 最后面的那個(gè) % 需要4個(gè)% 去代替(raid = HF-)select_sql = ’’’ select * from RESIDENTIAL_AREA where RA_ID like ’%s%%%%’ ’’’ % (raid) #@ 3 - python 代碼中 輸出結(jié)果為:print(select_sql) select * from RESIDENTIAL_AREA where RA_ID like ’HF-%%’
以上這篇Python處理mysql特殊字符的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python sorted排序方法如何實(shí)現(xiàn)2. Python基于requests實(shí)現(xiàn)模擬上傳文件3. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車4. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題5. python利用opencv實(shí)現(xiàn)顏色檢測(cè)6. Python文本文件的合并操作方法代碼實(shí)例7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫(huà)特效9. asp讀取xml文件和記數(shù)10. Python獲取B站粉絲數(shù)的示例代碼
