MySQL table data:
Demo.sql content
CREATE TABLE demo (ID int,product varchar (50), Price decimal (18,2), Quantity int,amount decimal (18,2), OrderDate datetime); INSERT INTO Demoselect1,'AAA', 15.2,5,76,'2017-09-09'Union Allselect2,'BBB', 10,6,60,'2016-05-18'Union Allselect3,'CCC', 21, 11,231,'2014-07-11'Union Allselect4,'DDD', 55, 2,110,'2016-12-24'Union Allselect5,'EEE', 20,4,80,'2017-02-08'Union Allselect6,'FFF', 45,2,90,'2016-08-19'Union Allselect7,'GGG', 33, 5,165,'2017-10-11'Union Allselect8,'HHH', 5, 40,200,'2014-08-30'Union Allselect9,'III', 3,20,60,'2015-02-25'Union Allselect10,'JJJ', 10, 15,150,'2015-11-02';
The implementation results are as follows:
Python code:
1 ImportPymysql2 ImportPandas as PD3 Importplotly.plotly4 ImportPlotly.graph_objs as PG5 6 7 defBar_chart (host, port, user, passwd, dbname, Charset,output_path):8 Try:9conn =Pymysql. Connection (Tenhost=Host, Oneport=Port, AUser=User, -Passwd=passwd, -db=dbname, thecharset=CharSet - ) -Cur =conn.cursor () -Cur.execute ("SELECT * from demo;") + #the Cursor object executes the query using the MySQL query string and returns a tuple with multiple tuples-one for each row -rows =Cur.fetchall () + #print (rows) A at #It is easier to use Pandas's dataframe to process each row than to use a tuple containing tuples - #The following Python code fragment converts all rows to Dataframe instances -DF = PD. DataFrame ([[IJ forIjinchI forIinchrows]) - Print(DF) -Df.rename (columns={0:'ID', 1:'Product', 2:' Price', 3:'Quantity', 4:'Amount', 5:'OrderDate'}, Inplace=True) - #df = Df.sort ([' lifeexpectancy '], ascending=[1]) in -Date_price = pg. Bar (x=df["Product"], y=df[" Price"], name='Price') toDate_quantity = pg. Bar (x=df["Product"], y=df["Quantity"], name='Quantity') +Date_amount = pg. Bar (x=df["Product"], y=df["Amount"], name='Total Price') -data =[Date_price, Date_quantity, Date_amount] the *Layout = pg. Layout (barmode='Group', title="sales of each product") $Fig = pg. Figure (Data=data, layout=layout)Panax NotoginsengPlotly.offline.plot (Fig, filename=Output_path) - the finally: + ifConn: A conn.close () the + - if __name__=='__main__': $Output_path ="c:/users/fuqia/desktop/bar.html" $Bar_chart ("localhost", 3306,"Root","123456","Test","UTF8", Output_path)
The output DF content is as follows:
Python uses plotly for visualizing data in MySQL