pyDAL教程展示了如何使用pyDAL数据库抽象层在Python中对数据库进行编程。我们在代码示例中使用了SQLite。
pyDAL
pyDAL是一个纯Python数据库抽象层。pyDAL模块为数据库后端动态生成指定方言的SQL。生成的代码可以在不同类型的数据库之间移植。
pyDAL安装
$ sudo pip3 install pyDAL
我们使用pip3工具来安装pyDAL。
pyDAL创建数据库表
在下面的例子中,我们创建了一个数据库表。
#!/usr/bin/python
from pydal import DAL, Field
db = DAL('sqlite://test.db', folder='dbs')
try:
db.define_table('cars', Field('name'), Field('price', type='integer'))
db.cars.insert(name='Audi', price=52642)
db.cars.insert(name='Skoda', price=9000)
db.cars.insert(name='Volvo', price=29000)
db.cars.insert(name='Bentley', price=350000)
db.cars.insert(name='Citroen', price=21000)
db.cars.insert(name='Hummer', price=41400)
db.cars.insert(name='Volkswagen', price=21600)
finally:
if db:
db.close()
该示例创建了一个包含七行的cars表。
db = DAL('sqlite://test.db', folder='dbs')
DAL表示一个数据库连接。它以数据库连接字符串作为第一个参数。我们连接到SQLite数据库。
db.define_table('cars', Field('name'), Field('price', type='integer'))
数据库表是用define_table定义的。如果它不存在,则创建它。它有两个字段:名称和价格。自动生成一个id字段。
db.cars.insert(name='Audi', price=52642)
我们使用insert向表中插入一个新行。该方法在db连接的cars表上调用。
$ ls dbs c95cf9bab36fcb04c2424cdf9be0f6e3_cars.table sql.log test.db
除了test.db数据库,我们还有一个扩展名为.table的迁移文件和一个日志文件。
pyDAL删除表
使用drop删除数据库表。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
cars = db.define_table('cars', Field('name'), Field('price', 'integer'))
cars.drop()
finally:
if db:
db.close()
在示例中,我们使用drop方法删除了cars表。
pyDAL选择行
使用select选择表格行。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price'))
rows = db().select(db.cars.ALL)
for row in rows:
print("{} {} {}".format(row['id'], row['name'], row['price']))
finally:
if db:
db.close()
在示例中,我们从cars表中检索所有行。
rows = db().select(db.cars.ALL)
我们使用select方法获取所有行。db.cars.ALL指示从表中选择所有列。
for row in rows:
print("{} {} {}".format(row['id'], row['name'], row['price']))
我们遍历每一行并打印其字段。
$ ./select_all_cars.py 1 Audi 52642 2 Skoda 9000 3 Volvo 29000 4 Bentley 350000 5 Citroen 21000 6 Hummer 41400 7 Volkswagen 21600
pyDAL排序
以下示例显示了如何使用pyDAL对数据进行排序。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db')
db.define_table('cars', Field('name'), Field('price', 'integer'))
rows = db(db.cars).select(orderby=db.cars.price)
for row in rows:
print("{} {} {}".format(row['id'], row['name'], row['price']))
print("**************************************")
rows = db(db.cars).select(orderby=~db.cars.price)
for row in rows:
print("{} {} {}".format(row['id'], row['name'], row['price']))
finally:
if db:
db.close()
该示例打印表中的所有行,并按价格升序和降序对它们进行排序。
rows = db(db.cars).select(orderby=db.cars.price)
排序是通过select方法的orderby参数完成的。
rows = db(db.cars).select(orderby=~db.cars.price)
要按降序排序,我们使用tilda字符。
$ ./order_by.py 5 Citroen 21000 7 Volkswagen 21600 3 Volvo 29000 4 Bentley 350000 6 Hummer 41400 1 Audi 52642 2 Skoda 9000 ************************************** 2 Skoda 9000 1 Audi 52642 6 Hummer 41400 4 Bentley 350000 3 Volvo 29000 7 Volkswagen 21600 5 Citroen 21000
pyDAL限制数据输出
数据输出可以通过select方法的limitby参数来限制。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price', 'integer'))
rows = db(db.cars).select(limitby=(2, 5))
for row in rows:
print("{} {} {}".format(row['id'], row['name'], row['price']))
finally:
if db:
db.close()
在代码示例中,我们将输出限制为偏移量为2的三行。
$ ./limit_by.py 3 Volvo 29000 4 Bentley 350000 5 Citroen 21000
pyDAL计数行
通过count,我们可以获得表格中的行数。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price', 'integer'))
n = db(db.cars.id).count()
print("There are {} rows in the table".format(n))
finally:
if db:
db.close()
在示例中,我们打印了cars表中的行数。
$ ./count_rows.py There are 7 rows in the table
表格中有七行。
pyDALJSON输出
我们可以通过as_json获取JSON格式的数据。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price', 'integer'))
rows = db(db.cars).select()
print(rows.as_json())
finally:
if db:
db.close()
该示例以JSON格式显示所有行。
$ ./json_output.py
[{"id": 1, "price": 52642, "name": "Audi"},
{"id": 2, "price": 9000, "name": "Skoda"},
{"id": 3, "price": 29000, "name": "Volvo"},
{"id": 4, "price": 350000, "name": "Bentley"},
{"id": 5, "price": 21000, "name": "Citroen"},
{"id": 6, "price": 41400, "name": "Hummer"},
{"id": 7, "price": 21600, "name": "Volkswagen"}]
pyDAL最后一条SQL
通过_lastsql可以找到pyDAL最后执行的SQL。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price', 'integer'))
# we ignore the result
db(db.cars.id).select(db.cars.name, db.cars.price)
print(db._lastsql)
finally:
if db:
db.close()
在示例中,我们在执行selectstatement时打印pyDAL执行的SQL。
$ ./lastsql.py
('SELECT "cars"."name", "cars"."price" FROM "cars" WHERE ("cars"."id" IS NOT NULL);', 0.0005686283111572266)
此SQL由pyDAL生成。
pyDAL执行原始SQL
我们可以使用executesql方法执行原始SQL。
#!/usr/bin/python
from pydal import DAL, Field
try:
db = DAL('sqlite://test.db', folder='dbs')
db.define_table('cars', Field('name'), Field('price', 'integer'))
data = db.executesql('SELECT * FROM cars WHERE id=6')[0]
print(data)
finally:
if db:
db.close()
在示例中,我们使用executesql执行SQLSELECT语句。
$ ./raw_sql.py (6, 'Hummer', '41400')
在本教程中,我们使用pyDAL来处理SQLite数据库。
访问Python教程或列出所有Python教程。
