Retrieving live data from MySQL Database

In one of my posts, I have mentioned how to collect live data into your MySQL database. In this post, I’ll explain you how to retireve this live data from your MySQL database and then use it for calculations.

“mydatabase” has a table called “ticker”. This table has two columns. The first column is “time” and the second column is “price”.

The values of the “time” column are timestamps and the values of the price column are live prices.

Step 1 : Let us being by importing the necessary modules.

Step 2 : Creating an empty list.

Here we have created an empty list, which we can populate with live data later on by appending.

Step 3 : Writing a function to make database connection and then retrieve the data

A very important thing to note here is that we care making the database connection inside the function. That’s because it has to be live. If you don’t do it like this, you will be getting stale data.

On order to fetch live data, you will have to connect to your database each and every time a new data is being posted.

Also, note that retrieving data from cursor.fetchall() is not very simple, as it produces a list of tuples. Hence, I had to create multiple variables to fetch this data.

You’ll notice that I’have used an SQL sub-query to get the last record. For that purpose I first created a column that was timestamped and then I used the max() function of SQL to get the last entered record.

Step 4 : Writing a function to use the retrieved data

Here, I have used “ltp[-1]” , to get the last item of the list.

Step 5 : Enabling threading

If you do not employ threading, then one function will wait for the other function to complete & hence, the purpose of getting live data will be defeated. Hence, thread all your functions.

The Entire Code