python中执行sql语句_python中使用原生态sql语句

Django中执行sql语句有两种方式:

1.object_list=Object.raw('select top 10 from Table where a=1')

如果你使用的是mysql数据库,这里就会出错,因为MySQL不支持top写法,可以换成:select * from table where a=1 limit 10

Paginator(list(object_list),8)#这里需要使用list(),主要是将object_list转换为list类型。不然你会在len(object_list)的时候出错,因为object_list没有这个方法

2.

from django.db import connection

cursor = connection.cursor()

cursor.execute("SELECT foo FROM bar WHERE baz =%s", [self.baz])

row = cursor.fetchone()

如果你的SQL语句改变了数据库中的数据 -- 比如你使用了 DELETE 或 UPDATE 语句. 你需要调用 connection.commit() 来使你的修改生效. 例子:

from django.db import connection

cursor = connection.cursor()

cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz])

connection.commit()

打印Django里面的sql语句

from django.db import connection

test.objects.filter(******)

print connection.queries

Python中使用mysql

import MySQLdb

db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',port=3306,charset='utf8')

cursor = db.cursor()

cursor.execute(´select * from table´)

rs = cursor.fetchall()

print rs

返回字典类型

import MySQLdb

import MySQLdb.cursors

db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',port=3306,charset='utf8',cursorclass = MySQLdb.cursors.DictCursor)

cursor = db.cursor()

cursor.execute(´select * from table´)

rs = cursor.fetchall()

print rs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值