hwdocker/filler/filler_db.py

33 lines
771 B
Python
Raw Normal View History

2024-11-23 14:00:50 +00:00
import os
import time
import pymysql
import csv
db_config = {
'host': 'db',
'user': os.getenv('MYSQL_USER'),
'password': os.getenv('MYSQL_PASSWORD'),
'db': os.getenv('MYSQL_DATABASE'),
}
while True:
print("Try connect to db")
try:
connection = pymysql.connect(**db_config)
break
except pymysql.MySQLError:
time.sleep(3)
print("")
with connection.cursor() as cursor, open('data.csv', 'r') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cursor.execute("INSERT INTO data (name, age) VALUES (%s, %s)", (row['name'], row['age']))
connection.commit()
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM data")
for row in cursor.fetchall():
print(row)