print ('Files in Drive:')!ls drive/AI
Files in Drive:
database.sqlite
Reviews.csv
Untitled0.ipynb
fine_food_reviews.ipynb
Titanic.csv
When I run the above code in Google Colab, clearly my sqlite file is present in my drive. But whenever I run some query on this file, it says
# using the SQLite Table to read data.
con = sqlite3.connect('database.sqlite') #filtering only positive and negative reviews i.e.
# not taking into consideration those reviews with Score=3
filtered_data = pd.read_sql_query("SELECT * FROM Reviews WHERE Score !=3",con)
DatabaseError: Execution failed on sql 'SELECT * FROM Reviews WHEREScore != 3 ': no such table: Reviews
Below you will find code that addresses the db setup on the Colab VM
, table creation
, data insertion
and data querying
. Execute all code snippets in individual notebook cells.
Note however that this example only shows how to execute the code on a non-persistent Colab VM. If you want to save your database to GDrive you will have to mount your Gdrive first (source):
from google.colab import drive
drive.mount('/content/gdrive')
and navigate to the appropriate file directory after.
Step 1: Create DB
import sqlite3conn = sqlite3.connect('SQLite_Python.db') # You can create a new database by changing the name within the quotes
c = conn.cursor() # The database will be saved in the location where your 'py' file is saved# Create table - CLIENTS
c.execute('''CREATE TABLE SqliteDb_developers([id] INTEGER PRIMARY KEY, [name] text, [email] text, [joining_date] date, [salary] integer)''')conn.commit()
Test whether the DB was created successfully:
!ls
Output:
sample_data SQLite_Python.db
Step 2: Insert Data Into DB
import sqlite3try:sqliteConnection = sqlite3.connect('SQLite_Python.db')cursor = sqliteConnection.cursor()print("Successfully Connected to SQLite")sqlite_insert_query = """INSERT INTO SqliteDb_developers(id, name, email, joining_date, salary) VALUES (1,'Python','[email protected]','2020-01-01',1000)"""count = cursor.execute(sqlite_insert_query)sqliteConnection.commit()print("Record inserted successfully into SqliteDb_developers table ", cursor.rowcount)cursor.close()except sqlite3.Error as error:print("Failed to insert data into sqlite table", error)
finally:if (sqliteConnection):sqliteConnection.close()print("The SQLite connection is closed")
Output:
Successfully Connected to SQLite
Record inserted successfully into SqliteDb_developers table 1
The SQLite connection is closed
Step 3: Query DB
import sqlite3conn = sqlite3.connect("SQLite_Python.db")cur = conn.cursor()
cur.execute("SELECT * FROM SqliteDb_developers")rows = cur.fetchall()for row in rows:print(row)conn.close()
Output:
(1, 'Python', '[email protected]', '2020-01-01', 1000)