sqlalchemy处理麻烦, 原sql处理

一.处理:

# -*- coding: utf-8-*-
import psycopg2

## 连接到一个给定的数据库
conn = psycopg2.connect(database="******", user="******",password="******", host="127.0.0.1", port="5432")
## 建立游标,用来执行数据库操作
cursor = conn.cursor()
print("====cursor====")
print(cursor)
## 执行SQL SELECT命令
# cursor.execute("select * from accounts")
# cursor.execute("select * from developer_key_account_bindings")
#cursor.execute("select count(*) from users")

sql = "select order_contexts.context_id, count(order_contexts.context_id) from mooc_orders inner join order_contexts on mooc_orders.id=order_contexts.mooc_order_id where mooc_orders.college_id=1 and order_contexts.context_type='book' GROUP BY order_contexts.context_id ORDER BY count(order_contexts.context_id) DESC LIMIT 10;"
cursor.execute(sql)

# t = cursor.execute("insert into developer_key_account_bindings(id,account_id,developer_key_id,workflow_state) values(1, 1, 2, 'on')")
# print("===t=====")
# print(t)
## 获取SELECT返回的元组
rows = cursor.fetchall()
print("=========rows=============")
print(rows)
#for row in rows:
#    print('id = ',row[0], '2 = ', row[1],'3 = ', row[2], '\n')

# 关闭游标
cursor.close()

# 关闭数据库连接
conn.close()

        

 

posted @ 2020-08-21 15:54  骑驴老神仙  阅读(176)  评论(0编辑  收藏  举报