Untitled

mail@pastecode.io avatar
unknown
python
a month ago
1.3 kB
2
Indexable
Never
import mariadb
import sys
import dbconfig
from datetime import datetime
import random

try:
	conn = mariadb.connect(
		user=dbconfig.user,
		password=dbconfig.password,
		host=dbconfig.host,
		port=dbconfig.port,
		)
except mariadb.Error as e:
	print(f'Error connecting to MariaDB Platform: {e}')
	sys.exit(1)

cursor = conn.cursor()

try:
    cursor.execute('CREATE DATABASE IF NOT EXISTS test_db')
    cursor.execute('USE test_db')
    # cursor.execute('DROP TABLE IF EXISTS test_table')
    cursor.execute(
    	'CREATE TABLE IF NOT EXISTS test_table (id MEDIUMINT NOT NULL AUTO_INCREMENT, session INT NOT NULL, measure_time DATETIME, sensor VARCHAR(16), value FLOAT, PRIMARY KEY (id))')
    cursor.execute('SELECT MAX(session) FROM test_table')
    session = cursor.fetchall()[0][0]
    session = (1 if session is None else session + 1)
    measure_time = datetime.now()
    params = [
    	(session, measure_time, 'TMP36', random.random()*100),
    	(session, measure_time, 'TMP37', random.random()*100),
    	(session, measure_time, 'TMP38', random.random()*100),
    ]
    cursor.executemany('INSERT INTO test_table (session, measure_time, sensor, value) VALUES (?, ?, ?, ?)', params)
    conn.commit()

except mariadb.Error as e:
    print(f'Error: {e}')
Leave a Comment