Skip to content

Instantly share code, notes, and snippets.

@bluethon
Created October 16, 2016 04:58
Show Gist options
  • Save bluethon/9ec1118ec62acc16914b8e95292f907b to your computer and use it in GitHub Desktop.
Save bluethon/9ec1118ec62acc16914b8e95292f907b to your computer and use it in GitHub Desktop.
django执行SQL语句
from django.db import connection, transaction
cursor = connection.cursor() # 获得一个游标(cursor)对象
cursor.execute('update order_invoiceinfo set type = 1')
transaction.commit() # 提交到数据库
# # 更新操作
# cursor.execute('update other_other2 set name ="李四" where id=%s', [3]) # 执行sql语句
# transaction.commit_unless_managed() # 提交到数据库
# # 查询操作
# cursor.execute('select * from other_other2 where id>%s', [1])
# raw = cursor.fetchone() # 返回结果行 或使用 #raw = cursor.fetchall()
#
# # 如果连接多个数据库则使用django.db.connections
# from django.db import connections
# _cursor = connections['other_database'].cursor()
# 如果执行了更新、删除等操作
# transaction.commit_unless_managed(using='other_databases')
# return render_to_response('other/sql.html', {'raw': raw})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment