Saving data to MySQL with Python

import mysql.connector
from time import sleep
import random
import sys

## C:\ProgramData\MySQL\MySQL Server 8.0\my.ini
## https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html#caching-sha2-pluggable-authentication-installation

try:
    username = "yourusername"; password="yourpassword";
    database="yourdatabase";host="localhost";

    cnx = mysql.connector.connect(user=username, password=password,
                                  host=host,database=database)
    cursor = cnx.cursor()
    print("Successfully connected to database!")
    
    update = True
    while update:
        try:
            value = random.randint(0,1024) 
            sensor_value = value
            print("Sensor value:", sensor_value)
            insert_statement = "INSERT INTO lights (light_value) VALUES (%                                       (light_value)s)"
            data = { 'light_value': sensor_value }
            cursor.execute(insert_statement, data )

            # Make sure data is committed to the database
            cnx.commit()
            print("Wait 5 secs before getting next light values..")
            sleep(5)
        except mysql.connector.Error as err:
            print(err)
        except KeyboardInterrupt:
            update = False
            cursor.close()
            cnx.close()
        except:
            print("Error while inserting data...")
            print(sys.exc_info()[0])
            print(sys.exc_info()[1])
except:
    print(sys.exc_info()[0])
    print(sys.exc_info()[1])
   

Comments

Popular posts from this blog

How to create an organizational chart in your webpage using Google Organization Chart Tools