cedroid

Fetch data from MySQL to Google Sheets

Sep 25th, 2023
857
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | Source Code | 0 0
  1. import pymysql
  2. import gspread
  3. from oauth2client.service_account import ServiceAccountCredentials
  4.  
  5. # Google Sheets API setup
  6. def google_sheet_setup(sheet_name, worksheet_name):
  7.     scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets",
  8.              "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
  9.  
  10.     creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
  11.     client = gspread.authorize(creds)
  12.     sheet = client.open(sheet_name)
  13.     worksheet = sheet.worksheet(worksheet_name)
  14.     return worksheet
  15.  
  16. # MySQL database connection
  17. def mysql_connection():
  18.     connection = pymysql.connect(host='localhost',
  19.                                  user='your_username',
  20.                                  password='your_password',
  21.                                  db='your_database_name')
  22.     return connection
  23.  
  24. # Fetch data from MySQL and insert into Google Sheet
  25. def transfer_data(worksheet, connection):
  26.     cursor = connection.cursor()
  27.     query = "SELECT * FROM your_table_name"
  28.     cursor.execute(query)
  29.     rows = cursor.fetchall()
  30.     for i, row in enumerate(rows):
  31.         worksheet.append_row(list(row))
  32.  
  33. # Main function
  34. if __name__ == '__main__':
  35.     worksheet = google_sheet_setup("Your Google Sheet Name", "Your Worksheet Name")
  36.     connection = mysql_connection()
  37.     transfer_data(worksheet, connection)
  38.     connection.close()
  39.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment