python第三方库系列之十一--django.db的connection库
来源:互联网 发布:长虹网络电视连不上wf 编辑:程序博客网 时间:2024/05/18 09:50
平时用django去向数据库中读写数据都是用的Model,直接molel.objects.filter(Q())或者model.objects.get(Q())等读取数据。然而这样的Q()查询SQL语句就必须符合django ORM的规范,今天想总结的是用connection库和原生的SQL语句读写数据库。
4. 总结,在django中如果加上2个“%”还报错,就加上4个“%”,所以写成这样:
from django.db import connectionSQL_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 connectionSQL_str = "select * from book where name LIKE '%%%%xxx%%%%'"cursor = connection.cursor()cursor.execute(SQL_str)domain_and_record_db_datas = cursor.fetchall()成功了!
0 0
- python第三方库系列之十一--django.db的connection库
- python第三方库系列之二十一--python django的权限管理库
- python第三方库系列之十八--python/django test库
- python第三方库系列之四--django自带分页工具Paginator
- Django 第三方库
- python第三方库系列之二十六--virtualenv库
- python第三方库系列之二十三--路径库
- python第三方库系列之二--time库
- python第三方库系列之六--traceback库
- python第三方库系列之七--logging库
- python第三方库系列之八--uuid库
- python第三方库系列之九--os库
- python第三方库系列之十--commands库
- python第三方库系列之十二--多线程threading库
- python第三方库系列之十五--编码库
- python第三方库系列之十七--multiprocessing库
- python第三方库系列之二十五--pip库
- python第三方库系列之十九--python测试使用的mock库
- Photoshop中的标尺、参考线
- Flume NG 简介及配置实战
- JQuery的Ajax跨域请求的解决方案
- solr的相关操作(addDocument,flush,commit,rollback,optimize,close)解析
- Android 、混淆代码总结
- python第三方库系列之十一--django.db的connection库
- android 手机设备唯一标识
- eclipse使用笔记
- 体验C#——关于数组合并的简单算法的实现
- 找出买卖股票的最大收益及其时间
- JDK 7中的文件操作的新特性
- VC++的窗口句柄和窗口ID
- hadoop学习笔记1
- android sqlite查询数据时报错: get field slot from row 0 col -1 failed