Querying SQLite database file in Google Colab

孤街醉人 提交于 2020-01-16 19:47:29

问题


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 WHERE Score != 3 ': no such table: Reviews


回答1:


Try this instead. See what tables are there.

"SELECT name FROM sqlite_master WHERE type='table'"



回答2:


give similar sharable id to your database file just like you did with Reviews.csv

database_file=drive.CreateFile({'id':'your_sharable_id for sqlite file'}) database_file.GetContentFile('database.sqlite')




回答3:


If you are trying to access the files from your google drive, you need to mount the drive first:

from google.colab import drive
drive.mount('/content/drive')

After you do this, right click on the file that you intend to read in colab session and select 'Copy Path'and paste it in the connection string.

con = sqlite3.connect('/content/database.sqlite')

You can now read the file.




回答4:


con = sqlite3.connect('database.sqlite')
filtered_data = pd.read_sql_query("SELECT * FROM Reviews WHERE Score !=3",con)

If you are executing it twice you will definitely end with this type of error.Execute it exactly once without any fail.

If you get any error then remove

database.sqlite

this file and extract it again.This time execute it again without any fail/error .This worked for me .




回答5:


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 sqlite3

conn = 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 sqlite3

try:
    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','MakesYou@Fly.com','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 sqlite3

conn = 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', 'MakesYou@Fly.com', '2020-01-01', 1000)



来源:https://stackoverflow.com/questions/50461696/querying-sqlite-database-file-in-google-colab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!