Python 格式化来自cursor.execute的结果
我需要帮助将我的结果显示为金额、折扣金额和月份。我可以在MySQL工作台上完成,但不能通过Python。 这是我的密码Python 格式化来自cursor.execute的结果,python,Python,我需要帮助将我的结果显示为金额、折扣金额和月份。我可以在MySQL工作台上完成,但不能通过Python。 这是我的密码 #! /usr/bin/env python # Importing connector import mysql.connector conn = None #Opening a connection try: conn = mysql.connector.Connect(host="localhost", user="root",password="Karima
#! /usr/bin/env python
# Importing connector
import mysql.connector
conn = None
#Opening a connection
try:
conn = mysql.connector.Connect(host="localhost", user="root",password="Karimanzira1978!", database="classicmodels")
print("Connected to MySQL!")
except Exception as ex:
print ("cannot connect to MySQL : exception : " + str(ex))
# Setting a cursor
cursor1 = conn.cursor()
cursor2= conn.cursor()
c = conn.cursor()
cursor1.execute("SELECT sum(amount), sum(amount *.99) as discounted_amount, paymentDate from payments where paymentDate >= '2003-12-01' AND paymentDate <='2003-12-31'")
print(cursor2.fetchall())
cursor2.execute("SELECT sum(amount), sum(amount *.99) as discounted_amount, paymentDate from payments where paymentDate >= '2004-12-01' AND paymentDate <='2004-12-31'")
print(cursor2.fetchall())
conn.commit()
conn.close
您可以使用熊猫模块的数据帧
首先:python-m pip install-U pandas为您的python版本安装pandas
第二个导入是从熊猫导入数据帧
然后,以第二个游标为例,将.execute中的数据存储到一个变量中,如下所示,只需在游标2.execute前面添加r=即可:
r = cursor2.execute("SELECT sum(amount), sum(amount *.99) as discounted_amount, paymentDate from payments where paymentDate >= '2004-12-01' AND paymentDate <='2004-12-31'")
现在,将fetchall存储到数据帧中:
df=DataFramer.fetchall
最后,设置dataframe的列:
df.columns=r.keys
您应该能够使用:df.head查看表的前5行
参考文献:
接下来,您可能还想看看pandas.read_sql函数。您向它传递一个SQL查询和一个数据库连接,它将为您完成将其读入数据帧的所有工作
例如:
导入mysql.connector
从导入读取sql
conn=无
打开连接
尝试:
conn=mysql.connector.Connecthost=localhost,user=root,password=Karimanzira1978!,数据库=classicmodels
打印连接到MySQL!
例外情况除外,例如:
打印无法连接到MySQL:异常:+strex
查询=从paymentDate>=“2003-12-01”和paymentDate的付款中选择sumamount,sumamount*.99作为折扣金额,paymentDate