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()
成功了!