码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2014-12-04 12:13:16      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:python   django   sql   like   cursor object has no   

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

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

标签:python   django   sql   like   cursor object has no   

原文地址:http://blog.csdn.net/wenph2008/article/details/41721511

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!