Step 1 : Import the necessary modules
|
1 2 |
import mysql.connector import time |
Step 2 : Write the code to make database connection
|
1 2 3 4 5 6 7 |
connection = mysql.connector.connect( host = "localhost", user = "root", password="yourpassword", database = "mydatabase" ) cursor = connection.cursor() |
Step 3 : Write the code to insert live data into your MySQL database
Here I have created an imaginary function to create live data. In real life, this function could be a websocket connection that gets realtime data from the stock exchange.
|
1 2 3 4 5 6 7 8 9 10 |
for i in range(20): sql="insert into ticker (time,price) values (%s,%s)" val = (time.time(),i) cursor.execute(sql,val) cursor.execute("select price from ticker") print(cursor.fetchall()) i=i+1 time.sleep(0.5) connection.commit() |
Step 4 : Close the connection
|
1 |
connection.close() |
The Entire Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import mysql.connector import time connection = mysql.connector.connect( host = "localhost", user = "root", password="yourpassword", database = "mydatabase" ) cursor = connection.cursor() for i in range(20): sql="insert into ticker (time,price) values (%s,%s)" val = (time.time(),i) cursor.execute(sql,val) cursor.execute("select price from ticker") print(cursor.fetchall()) i=i+1 time.sleep(0.5) connection.commit() connection.close() |