使用 python 打开数据库文件 (.db)

Ho *_*ong 5 python sqlite

我有一个 SQLite3 格式的数据库文件 .db,我试图打开它以查看其中的数据。下面是我使用 python 编码的尝试。

    import sqlite3

    # Create a SQL connection to our SQLite database
    con = sqlite3.connect(dbfile)

    cur = con.cursor()

    # The result of a "cursor.execute" can be iterated over by row
    for row in cur.execute("SELECT * FROM "):
    print(row)

    # Be sure to close the connection
    con.close()
Run Code Online (Sandbox Code Playgroud)

对于这一行("SELECT * FROM "),我知道您必须在“FROM”一词之后放入表格的标题,但是,由于我什至无法首先打开文件,因此我不知道该放置什么标题。因此,我该如何编码才能打开数据库文件以读取其内容?

Seb*_*Nik 28

所以,你分析得对。在 FROM 之后,您必须输入表名。但你可以这样找到它们:

SELECT name FROM sqlite_master WHERE type = 'table'
Run Code Online (Sandbox Code Playgroud)

在代码中,它看起来像这样:

# loading in modules
import sqlite3

# creating file path
dbfile = '/home/niklas/Desktop/Stuff/StockData-IBM.db'
# Create a SQL connection to our SQLite database
con = sqlite3.connect(dbfile)

# creating cursor
cur = con.cursor()

# reading all table names
table_list = [a for a in cur.execute("SELECT name FROM sqlite_master WHERE type = 'table'")]
# here is you table list
print(table_list)

# Be sure to close the connection
con.close()
Run Code Online (Sandbox Code Playgroud)

这对我来说非常有效。您已经完成的数据读取只需粘贴到表名中即可。


小智 7

如果您想将数据视为 pandas 数据框进行可视化分析,也可以使用以下方法。

import pandas as pd
import sqlite3
import sqlalchemy 

try:
    conn = sqlite3.connect("file.db")    
except Exception as e:
    print(e)

#Now in order to read in pandas dataframe we need to know table name
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(f"Table Name : {cursor.fetchall()}")

df = pd.read_sql_query('SELECT * FROM Table_Name', conn)
conn.close()
Run Code Online (Sandbox Code Playgroud)