在Python中,數(shù)據(jù)庫并不是存儲大量結(jié)構(gòu)化數(shù)據(jù)的最簡單解決方案。dataset提供了一個簡單的抽象層,可以刪除大多數(shù)直接的 SQL 語句,而無需完整的 ORM 模型,數(shù)據(jù)庫可以像 JSON 文件或 NoSQL 存儲一樣使用。 特點(diǎn)
連接數(shù)據(jù)庫# connecting to a SQLite database db = dataset.connect('sqlite:///mydatabase.db')
# connecting to a MySQL database with user and password db = dataset.connect('mysql://user:password@localhost/mydatabase')
# connecting to a PostgreSQL database db = dataset.connect('postgresql://scott:tiger@localhost:5432/mydatabase') 存儲數(shù)據(jù)
將數(shù)據(jù)存儲在只需傳遞一個dict即可插入。不需要創(chuàng)建列名稱和年齡——數(shù)據(jù)集會自動執(zhí)行此操作: # Insert a new record. table.insert(dict(name='John Doe', age=46, country='China'))
# dataset will create 'missing' columns any time you insert a dict with an unknown key table.insert(dict(name='Jane Doe', age=37, country='France', gender='female')) table.update(dict(name='John Doe', age=47), ['name']) id 列。使用with dataset.connect() as tx: tx['user'].insert(dict(name='John Doe', age=46, country='China')) 通過調(diào)用方法獲得相同的功能begin(), commit()并rollback() 明確:
也支持嵌套事務(wù):
檢查數(shù)據(jù)庫和表
列出表中所有可用的列
使用 len() 獲得表中的總行數(shù):
從表中讀取數(shù)據(jù)現(xiàn)在讓我們從表中獲取一些真實數(shù)據(jù): users = db['user'].all() 如果我們只是想遍歷表中的所有行,我們可以省略all():
我們可以使用find()搜索特定條目find_one(): # All users from China chinese_users = table.find(country='China')
# Get a specific user john = table.find_one(name='John Doe')
# Find multiple at once winners = table.find(id=[1, 3, 7])
# Find by comparison operator elderly_users = table.find(age={'>=': 70}) possible_customers = table.find(age={'between': [21, 80]})
# Use the underlying SQLAlchemy directly elderly_users = table.find(table.table.columns.age >= 70) 使用 distinct()我們可以在一個或多個列中獲取一組具有唯一值的行:
最后,您可以使用row_type參數(shù)來選擇返回結(jié)果的數(shù)據(jù)類型: import dataset from stuf import stuf
db = dataset.connect('sqlite:///mydatabase.db', row_type=stuf) 現(xiàn)在內(nèi)容將在對象中返回stuf(基本上,dict 其元素可以作為屬性 ( item.name) 以及索引 ( item['name']) 訪問的對象。 運(yùn)行自定義 SQL 查詢當(dāng)然,您使用數(shù)據(jù)庫的主要原因是您希望使用 SQL 查詢的全部功能。下面是你如何運(yùn)行它們dataset:
該query()方法還可用于訪問底層的SQLAlchemy 核心 API,它允許以編程方式構(gòu)建更復(fù)雜的查詢: table = db['user'].table statement = table.select(table.c.name.like('%John%')) result = db.query(statement) |
|