Store Google Sheets data into SQLite Database using Python
In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let’s get stared.
Enabling the APIs and creating the credentials
- Go to Marketplace in Cloud Console.
- Click on ENABLE APIS AND SERVICES
- Then Search for Google Drive API and enable it
- Then go to the Credentials tab on the left navigation bar on the screen.
- Then click on Create Credentials then select Service Account Key
- Then create a new service account by giving it a name and set the Role to Editor under the Projects sub-field and keep the key type as JSON and click on Create button. Keep the Downloaded JSON safely.
- After all these steps are done your page should look something like this.
- Again go to Dashboard and follow the same steps. This time search for Google Sheets and enable the API.
After enabling the API lets’ create the google form.
Creating the Google Form:
- Create a Google Form. Here, we kept a simple form with only two fields.
- Make the Google form accept responses in Google Sheets.
- Then lookup the downloaded JSON file for the field client_email and copy that email.
- Open the newly created spreadsheet and click on the share option and type the paste the client_email there.
After giving access to the client email, it should look something like this. The top email will be your personal email and the bottom one will be the client_email
So we are done with the setting up. Now, let’s get to code. Before we begin, let’s just understand the flow.
- We will create a database and a table according to the entry schemas of the form.
- Make a connection to the sheets via the API and fetch all the rows.
- Execute insert query to insert the row data from sheets to the database.
- First, we initialize the credentials from the service account JSON.
- We then use these credentials object to access the Sheet that we generated from the Google Form.
- Once we have the access to the sheets, we simply extract all the rows at once to reduce the number of API calls.
- Now, we first make our connection to the database. Here, we use the sqlite database for simplicity. You can use any type of database, all you need to do is pass on the connection string.
- Once the connection is established, we create the table (if it does not exist)
- Once the table is ready, we pass the fetched rows to the table. We simply iterate over all the rows obtained and then pass on each column value in the row to the database.
As you can see, we now successfully have the data in our database.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course