Querying SQLite database file in Google Colab

2024/10/14 11:17:23
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

Answer

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)

https://en.xdnf.cn/q/117962.html

Related Q&A

AttributeError: function object has no attribute self

I have a gui file and I designed it with qtdesigner, and there are another py file. I tried to changing button name or tried to add item in listwidget but I didnt make that things. I got an error messa…

Find file with largest number in filename in each sub-directory with python?

I am trying to find the file with the largest number in the filename in each subdirectory. This is so I can acomplish opening the most recent file in each subdirectory. Each file will follow the namin…

Selenium Python - selecting from a list on the web with no stored/embedded options

Im very new to Python so forgive me if this isnt completely comprehensible. Im trying to select from a combobox in a webpage. All the examples Ive seen online are choosing from a list where the options…

How to use a method in a class from another class that inherits from yet another class python

I have 3 classes :class Scene(object):def enter(self):passclass CentralCorridor(Scene):def enter(self):passclass Map(object):def __init__(self, start_game): passAnd the class map is initiated like this…

Finding common IDs (intersection) in two dictionaries

I wrote a piece of code that is supposed to find common intersecting IDs in line[1] in two different files. On my small sample files it works OK, but on my bigger files does not. I cannot figure out wh…

Run command line containing multiple strings from python script

Hello i am trying to autogenerate a PDF, i have made a python script that generates the wanted PDF but to generate it i have to call my_cover.py -s "Atsumi" -t "GE1.5s" -co "Ja…

Identify value across multiple columns in a dataframe that contain string from a list in python

I have a dataframe with multiple columns containing phrases. What I would like to do is identify the column (per row observation) that contains a string that exists within a pre-made list of words. Wi…

ipython like interpreter for ruby

I come from python background and am learning ruby. IPython is really awesome. I am new to ruby now, and wanted to have some sort of ipython things. As of now am having tough time, going along ruby lin…

Django dynamic verification form

Im trying to create a verification form in Django that presents a user with a list of choices, only one of which is valid.For example, for a user whose favourite pizza toppings includes pineapple and r…

Any method to denote object assignment?

Ive been studying magic methods in Python, and have been wondering if theres a way to outline the specific action of:a = MyClass(*params).method()versus:MyClass(*params).method()In the sense that, perh…