Store Google Sheets data into SQLite Database using Python
Last Updated :
29 Dec, 2022
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
Google Form:
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.
Approach:
- 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.
Code:
Python3
import sqlite3
from sqlite3 import Error
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def get_from_sheet():
sheet_name = "Details (Responses)"
config = { Your_API
}
scope = [
]
creds_obj = ServiceAccountCredentials.from_json_keyfile_dict(config, scope)
client = gspread.authorize(creds_obj)
sheet = client. open (sheet_name).sheet1
return sheet.get_all_values()
class SQLite:
DB_NAME = "db.sqlite"
def __init__( self ):
self .conn = self .create_connection()
self ._get_or_create_table()
@classmethod
def create_connection( cls ):
conn = None
try :
conn = sqlite3.connect( cls .DB_NAME)
return conn
except Error as e:
print (e)
return conn
def _get_or_create_table( self ):
create_table_sql =
try :
c = self .conn.cursor()
c.execute(create_table_sql)
except Error as e:
print (e)
def add_data_to_table( self , rows: list ):
c = self .conn.cursor()
insert_table_sql =
for row in rows[ 1 :]:
c.execute(insert_table_sql, tuple (row))
self .conn.commit()
c.close()
if __name__ = = '__main__' :
data = get_from_sheet()
sqlite_util = SQLite()
sqlite_util.add_data_to_table(data)
|
Output:
As you can see, we now successfully have the data in our database.
Share your thoughts in the comments
Please Login to comment...