python第三方库系列之十一--django.db的connection库
2014-12-04 11:21
495 查看
平时用django去向数据库中读写数据都是用的Model,直接molel.objects.filter(Q())或者model.objects.get(Q())等读取数据。然而这样的Q()查询SQL语句就必须符合django ORM的规范,今天想总结的是用connection库和原生的SQL语句读写数据库。
1. 平时的LIKE方法是:
这条语句相当于:
如果写成这样,打印出来的SQL语句是可以在SQL命令行下运行的,但在我的django中会报出以下错误:
4. 总结,在django中如果加上2个“%”还报错,就加上4个“%”,所以写成这样:
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第三方库系列之二十一--python django的权限管理库
- python第三方库系列之四--django自带分页工具Paginator
- python第三方库系列之二十六--virtualenv库
- python,sql,sqlite3,django,db,command line
- Python+Django+SAE系列教程2-----Python种的函数、模块和数据结构
- Python+Django+SAE系列教程4-----操作文件
- Python+Django+SAE系列教程3-----Python中的面向对象编程
- sphinx系列之用python和django调用你的sphinx(五)
- python django系列(一)
- Python系列视频教程: Django【13讲】第13讲 表单使用
- Python系列视频教程: Django【13讲】第12讲 数据展示
- python第三方库系列之二十四--http-web库
- Python学习系列十一:动态类型
- Python系列视频教程: Django【13讲】第五讲 URL配置
- Python系列视频教程: Django【13讲】第四讲 运算符-表达式
- Python+Django+SAE系列教程1-----Python环境和基本语法
- Python&Django学习系列之-激活管理界面
- Python系列视频教程: Django【13讲】第三讲 模板变量的使用
- Python系列视频教程: Django【13讲】第七讲 数据库使用1
- Python+Django+SAE系列教程1-----Python环境和基本语法