【问题标题】:Querying SQLite database file in Google Colab在 Google Colab 中查询 SQLite 数据库文件
【发布时间】:2018-10-31 20:50:57
【问题描述】:
print ('Files in Drive:')

!ls drive/AI

云端硬盘中的文件:

database.sqlite
Reviews.csv
Untitled0.ipynb
fine_food_reviews.ipynb
Titanic.csv

当我在 Google Colab 中运行上述代码时,很明显我的 sqlite 文件存在于我的驱动器中。但是每当我对这个文件运行一些查询时,它都会说

# 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: sql 'SELECT * FROM Reviews WHERE 执行失败 Score != 3 ': 没有这样的表:评论

【问题讨论】:

    标签: python sql pandas sqlite google-colaboratory


    【解决方案1】:

    您将在下面找到地址db setup on the Colab VMtable creationdata insertiondata querying 的代码。在单个笔记本单元格中执行所有代码 sn-ps。

    但请注意,此示例仅显示如何在非持久 Colab VM 上执行代码。如果您想将数据库保存到 GDrive,您必须先挂载您的 Gdrive (source):

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

    navigate之后到相应的文件目录。


    第 1 步:创建数据库

    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()
    

    测试DB是否创建成功:

    !ls
    

    输出:

    sample_data SQLite_Python.db


    第 2 步:将数据插入数据库

    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")
    

    输出:

    成功连接到 SQLite

    记录成功插入SqliteDb_developers表1

    SQLite 连接已关闭


    第 3 步:查询数据库

    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()
    

    输出:

    (1, 'Python', 'MakesYou@Fly.com', '2020-01-01', 1000)

    【讨论】:

      【解决方案2】:

      试试这个。看看那里有什么桌子。

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

      【讨论】:

      • filtered_data = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'",con) print(filtered_data) 给我“Empty DataFrame Columns: [name] Index: []”跨度>
      • 所以它可以读取一个表,但是表是空的。您现在可以尝试确保 sqlite 文件中有一个包含正确数据的评论表。
      【解决方案3】:

      为您的数据库文件提供类似的可共享 ID,就像您对 Review.csv 所做的那样

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

      【讨论】:

        【解决方案4】:

        如果您尝试从您的 google 驱动器访问文件,您需要先挂载驱动器:

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

        完成此操作后,右键单击要在 colab 会话中读取的文件,然后选择“复制路径”并将其粘贴到连接字符串中。

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

        您现在可以读取文件了。

        【讨论】:

          【解决方案5】:
          con = sqlite3.connect('database.sqlite')
          filtered_data = pd.read_sql_query("SELECT * FROM Reviews WHERE Score !=3",con)
          

          如果你执行两次,你肯定会以这种类型的错误结束。只执行一次就不会失败。

          如果遇到任何错误,请删除

          数据库.sqlite

          这个文件并再次提取它。这次再次执行它,没有任何失败/错误。这对我有用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-05-14
            • 2011-08-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-03
            • 1970-01-01
            • 2017-03-22
            相关资源
            最近更新 更多