The following code plotmysql.py makes a simple 2D plot using data from a MySQL database:
import sysThe resulting file is a png image called plot.png. To run the code, type:
from pylab import *
import MySQLdb
db = MySQLdb.connect(sys.argv[1], sys.argv[2], sys.argv[3],
sys.argv[4])
cursor = db.cursor()
query = sys.argv[5]
cursor.execute(query)
result = cursor.fetchall()
t = []
s = []
for record in result:
t.append(record[0])
s.append(record[1])
plot(t, s, 'ko')
axis([min(t), max(t), min(s), max(s)])
title(query)
grid(True)
F = gcf()
DPI = F.get_dpi()
F.savefig('plot.png',dpi = (80))
python plotmysql.py [host] [user] [password] [database] [query]
The five required arguments here are the hostname of the MySQL database, username, passowrd, database and the query. For example:
python plotmysql.py localhost testuser testpass testdb "select x, y from data"
will plot column y versus column x from the table called data in the database called testdb. This query is obviously very simple, however a plot can of course be made from any query no matter how complex, provided there are 2 values per row in the set of results.
2 comments:
Great, tanx a lot!
Is it possible to read from multy mysql db (and graph a multy y-axis)
Worthful Python tutorial. Appreciate a lot for taking up the pain to write such a quality content on Python tutorial. Just now I watched this similar Python tutorial and I think this will enhance the knowledge of other visitors for sure. Thanks anyway.:-https://www.youtube.com/watch?v=qgOXopu4n7c&
Post a Comment