在Python中,數據庫并不是存儲大量結構化數據的最簡(jiǎn)單解決方案。dataset提供了一個(gè)簡(jiǎn)單的抽象層,可以刪除大多數直接的 SQL 語(yǔ)句,而無(wú)需完整的 ORM 模型,數據庫可以像 JSON 文件或 NoSQL 存儲一樣使用。
# connecting to a SQLite databasedb = dataset.connect('sqlite:///mydatabase.db')
# connecting to a MySQL database with user and passworddb = dataset.connect('mysql://user:password@localhost/mydatabase')
# connecting to a PostgreSQL databasedb = dataset.connect('postgresql://scott:tiger@localhost:5432/mydatabase')# get a reference to the table 'user'table = db['user']
將數據存儲在只需傳遞一個(gè)dict即可插入。不需要創(chuàng )建列名稱(chēng)和年齡——數據集會(huì )自動(dòng)執行此操作:
# 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 keytable.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'))db = dataset.connect()db.begin()try:db['user'].insert(dict(name='John Doe', age=46, country='China'))db.commit()except:db.rollback()
也支持嵌套事務(wù):
db = dataset.connect()with db as tx1:tx1['user'].insert(dict(name='John Doe', age=46, country='China'))with db as tx2:tx2['user'].insert(dict(name='Jane Doe', age=37, country='France', gender='female'))
>>> print(db.tables)[u'user']
列出表中所有可用的列user:
>>> print(db['user'].columns)[u'id', u'country', u'age', u'name', u'gender']
len()獲得表中的總行數:>>> print(len(db['user']))2
現在讓我們從表中獲取一些真實(shí)數據:
users = db['user'].all()如果我們只是想遍歷表中的所有行,我們可以省略all():
for user in db['user']:print(user['age'])
我們可以使用find()搜索特定條目find_one():
# All users from Chinachinese_users = table.find(country='China')
# Get a specific userjohn = table.find_one(name='John Doe')
# Find multiple at oncewinners = table.find(id=[1, 3, 7])
# Find by comparison operatorelderly_users = table.find(age={'>=': 70})possible_customers = table.find(age={'between': [21, 80]})
# Use the underlying SQLAlchemy directlyelderly_users = table.find(table.table.columns.age >= 70)使用 distinct()我們可以在一個(gè)或多個(gè)列中獲取一組具有唯一值的行:
# Get one user per countrydb['user'].distinct('country')
最后,您可以使用row_type參數來(lái)選擇返回結果的數據類(lèi)型:
import datasetfrom stuf import stuf
db = dataset.connect('sqlite:///mydatabase.db', row_type=stuf)現在內容將在對象中返回stuf(基本上,dict 其元素可以作為屬性 ( item.name) 以及索引 ( item['name']) 訪(fǎng)問(wèn)的對象。
當然,您使用數據庫的主要原因是您希望使用 SQL 查詢(xún)的全部功能。下面是你如何運行它們dataset:
result = db.query('SELECT country, COUNT(*) c FROM user GROUP BY country')for row in result:print(row['country'], row['c'])
該query()方法還可用于訪(fǎng)問(wèn)底層的SQLAlchemy 核心 API,它允許以編程方式構建更復雜的查詢(xún):
table = db['user'].tablestatement = table.select(table.c.name.like('%John%'))result = db.query(statement)聯(lián)系客服