My data is divided in two mysql databases with the same structure.
What I am trying to do is write a python script that extracts and appends the data from both databases, stores it in a variable or a text file (let's say somefile.csv) and then another script gets the data from the variable/text file and imports it in google sheets through the google sheets api. The caveat is that my data changes every day and I also want both scripts to update automatically (run each day and fetch the updated data, the first to rewrite the csv and the second the google sheet with the new data from the csv).
Is that possible?
What I have so far is:
The first script:
from mysql.connector import connect, Error
username = "user"
password = "pass"
connection_1 = connect(
host="hostaddress",
user=username,
password=password,
database="databasename"
)
connection_2 = connect(
host="hostaddress",
user=username,
password=password,
database="databasename"
)
cursor_1 = connection_1.cursor()
cursor_2 = connection_2.cursor()
q1 = open('query_db1.sql', 'r')
query1 = q1.read()
q1.close()
q2 = open('query_db2.sql', 'r')
query2 = q2.read()
q2.close()
try:
with connection_1:
with cursor_1:
cursor_1.execute(query_1)
for row in cursor_1.fetchall():
print(row)
with connection_2:
with cursor_2:
cursor_2.execute(query2)
for row in cursor_2.fetchall():
print(row)
except Error as e:
print(e)
The two problems I am facing in this script are:
- how to store the data from the executed queries in one variable or save it to one file?
- how to make that script query the databases every day and update the stored information?
In the second script, I have
from googleapiclient.discovery import build
from google.oauth2 import service_account
SERVICE_ACCOUNT_FILE = 'googleapicredentials.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
SAMPLE_SPREADSHEET_ID = 'SHEET_ID'
service = build('sheets', 'v4', credentials=creds)
request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range="Sheet1!A1", valueInputOption="USER_ENTERED", body={"values":"somefile.csv"}).execute()
Again, I don't know how to make that script update each day.