用 Python 和 pandas 读取 SQLite 数据
通过 pandas,可以将 SQLite 查询结果直接读入 DataFrame。SQL 命令和语法与 SQLite 课程中用过的相同。下面是把 pandas 和 SQLite 配合使用的例子:
import pandas as pd
import sqlite3
# Read sqlite query results into a pandas DataFrame
con = sqlite3.connect("data/portal_mammals.sqlite")
df = pd.read_sql_query("SELECT * from surveys", con)
# Verify that result of SQL query is stored in the dataframe
print(df.head())
con.close()
用 Python 和 pandas 访问 SQLite 数据库 最后更新于 2023 年 5 月 18 日|编辑本页 https://datacarpentry.org/python-ecology-lesson/instructor/09-working-with-sql.html
在 pandas DataFrame 中使用 SQL David Fagbuyiro 2023 年 10 月 17 日 https://medium.com/@davidfagb/using-sql-with-pandas-dataframes-1c36f57ea65d
一个 SQLite 数据库对应一个文件,会有什么问题?
一个完整的 SQL 数据库可以包含多张表、索引、触发器和视图,所有这些都保存在单个磁盘文件中。
- About sqlite. (n.d.). sqlite. Retrieved April 2, 2024, from https://www.sqlite.org/about.html
- thameera(2012 年 2 月 23 日)问:“据我所知,SQLite 把一个数据库存储在一个文件里。我担心这会降低大型数据库的性能。能否显式指定把不同的表存到不同的文件里?” Stack Overflow。https://stackoverflow.com/questions/9410011/multiple-files-for-a-single-sqlite-database
数据库大小上限
每个数据库由一个或多个“页”组成。同一数据库内的页大小相同。不同数据库可以选择不同的页大小,取值为 512 到 65536 字节之间的 2 的幂,包括两端。数据库文件最多有 4294967294 页。每页按 65536 字节计算,上限约为 281 TB,即 256 TiB,或约 281474 GB、256000 GiB。
开发者没有能达到这一上限的硬件,因此并未实测这个极限值。不过,他们已验证两种情况下 SQLite 都能合理地工作:数据库达到底层文件系统的单文件上限(通常远低于数据库理论上限),以及磁盘空间耗尽、数据库无法继续增长。
📓 说明: MySQL 等其他数据库的数据库文件也有类似量级的理论上限。
- Limits in sqlite. (n.d.). sqlite. Retrieved April 2, 2024, from https://www.sqlite.org/limits.html
怎样联结不同数据库中的表?
如果你使用的 SQLite 构建启用了 ATTACH(多数构建都会启用),就可以用 ATTACH 将另一个数据库文件附加到当前连接。可附加数据库的数量取决于编译参数 SQLITE_MAX_ATTACHED,默认是 10,具体值可能随构建而异;绝对上限为 125。
attach 'database1.db' as db1;
attach 'database2.db' as db2;
可以用下面的命令查看已连接的所有数据库:
sqlite> .tables.databases
然后就可以执行这样的查询:
select
*
from
db1.SomeTable a
inner join
db2.SomeTable b on b.SomeColumn = a.SomeColumn;
Note that "[t]he database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment".
- Brian Gideon(2011 年 7 月 26 日)答:只要 SQLite 构建启用了 ATTACH,就可以将其他数据库文件附加到当前连接;能附加多少个由编译时设置决定。Stack Overflow。https://stackoverflow.com/questions/6824717/sqlite-how-do-you-join-tables-from-different-databases/6824831#6824831
最多可附加多少个数据库?
ATTACH 是 SQLite 的扩展语句。它让两个或更多数据库关联到同一个连接上,使用起来如同一个数据库。同时附加的数量由 SQLITE_MAX_ATTACHED 限制,默认是 10,最多不能超过 125。
运行时可以用 sqlite3_limit(db,SQLITE_LIMIT_ATTACHED,size) 调低这个上限。