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()
成功了!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章