python第三方庫系列之十一--django.db的connection庫

    平時用django去向數據庫中讀寫數據都是用的Model,直接molel.objects.filter(Q())或者model.objects.get(Q())等讀取數據。然而這樣的Q()查詢SQL語句就必須符合django ORM的規範,今天想總結的是用connection庫和原生的SQL語句讀寫數據庫。
from django.db import connection
SQL_str = "select * from book"
cursor = connection.cursor()
cursor.execute(SQL_str)
domain_and_record_db_datas = cursor.fetchall()
    今天碰到一個特別奇葩的問題,修復了一下午才得以解決,就是SQL語句中的LIKE方法。看看一下是怎麼演變的:

1. 平時的LIKE方法是:

SQL_str = "select * from book where name LIKE 'xxx'"
這條語句相當於:
SQL_str = "select * from book where name = 'xxx'"
2. 爲了模糊查詢,應該這樣:
SQL_str = "select * from book where name LIKE '%xxx%'"
3. 但在python中,“%”是一個特殊字符,需要兩個“%%”才表示一個“%”,所以寫成這樣:

SQL_str = "select * from book where name LIKE '%%xxx%%'"
print SQL_str
# select * from book where name LIKE '%xxx%'

如果寫成這樣,打印出來的SQL語句是可以在SQL命令行下運行的,但在我的django中會報出以下錯誤:

'Cursor' object has no attribute '_last_executed'
我在網上找了很久,都說只要加上“%%”就行,我的就是報錯。於是我大膽的加上了“%%%%”,告訴編譯器我這個是百分號,居然OK了!
4. 總結,在django中如果加上2個“%”還報錯,就加上4個“%”,所以寫成這樣:

from django.db import connection
SQL_str = "select * from book where name LIKE '%%%%xxx%%%%'"
cursor = connection.cursor()
cursor.execute(SQL_str)
domain_and_record_db_datas = cursor.fetchall()
成功了!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章