1、PostgreSQL数据库
PostgreSQL是一种特性非常齐全的自由软件的对象-关系型数据库管理系统(ORDBMS),是以加州大学计算机系开发的POSTGRES,4.2版本为基础的对象关系型数据库管理系统。POSTGRES的许多领先概念只是在比较迟的时候才出现在商业网站数据库中。PostgreSQL支持大部分的SQL标准并且提供了很多其他现代特性,如复杂查询、外键、触发器、视图、事务完整性、多版本并发控制等。同样,PostgreSQL也可以用许多方法扩展,例如通过增加新的数据类型、函数、操作符、聚集函数、索引方法、过程语言等。另外,因为许可证的灵活,任何人都可以以任何目的免费使用、修改和分发PostgreSQL。
2、安装Pony和psycopg2
psycopg2是Python语言的PostgreSQL数据库接口,是对Psycopg 1.1.x版本进行的几乎完全的改写。主要优势在于完全支持Python DB API 2.0,以及安全的多线程支持。它适用于随时创建、销毁大量游标的、和产生大量并发INSERT、UPDATE操作的多线程数据库应用。Psycopg包内含 ZPsycopgDA,一个Zope数据库接口。
1)使用pip安装Pony
pip install pony
2)安装psycopg2
pip install psycopg2
3、Pony PostgreSQL常用操作
使用Pony ORM操作PostgreSQL进行数据增加、删除、修改和查询,示例代码如下,
from decimal import Decimal
from pony.orm import *
db = Database()
db.bind('postgres', user='root', password='admin',
host='localhost', database='db', port='5432')
class Customer(db.Entity):
id = PrimaryKey(int, auto=True)
name = Required(str)
email = Required(str, unique=True)
orders = Set("OrderInfo")
class OrderInfo(db.Entity):
id = PrimaryKey(int, auto=True)
total_price = Required(Decimal)
customer = Required(Customer)
items = Set("OrderItem")
class Product(db.Entity):
id = PrimaryKey(int, auto=True)
name = Required(str)
price = Required(Decimal)
items = Set("OrderItem")
class OrderItem(db.Entity):
quantity = Required(int, default=1)
order = Required(OrderInfo)
product = Required(Product)
PrimaryKey(order, product)
sql_debug(True)
db.generate_mapping(create_tables=True)
@db_session
def populate_database():
c1 = Customer(name='John Smith', email='john@example.com')
c2 = Customer(name='Matthew Reed', email='matthew@example.com')
c3 = Customer(name='Chuan Qin', email='chuanqin@example.com')
c4 = Customer(name='Rebecca Lawson', email='rebecca@example.com')
c5 = Customer(name='Oliver Blakey', email='oliver@example.com')
p1 = Product(name='Kindle Fire HD', price=Decimal('284.00'))
p2 = Product(name='Apple iPad with Retina Display', price=Decimal('478.50'))
p3 = Product(name='SanDisk Cruzer 16 GB USB Flash Drive', price=Decimal('9.99'))
p4 = Product(name='Kingston DataTraveler 16GB USB 2.0', price=Decimal('9.98'))
p5 = Product(name='Samsung 840 Series 120GB SATA III SSD', price=Decimal('98.95'))
p6 = Product(name='Crucial m4 256GB SSD SATA 6Gb/s', price=Decimal('188.67'))
o1 = OrderInfo(customer=c1, total_price=Decimal('292.00'))
OrderItem(order=o1, product=p1)
OrderItem(order=o1, product=p4, quantity=2)
o2 = OrderInfo(customer=c1, total_price=Decimal('478.50'))
OrderItem(order=o2, product=p2)
o3 = OrderInfo(customer=c2, total_price=Decimal('680.50'))
OrderItem(order=o3, product=p2)
OrderItem(order=o3, product=p4, quantity=2)
OrderItem(order=o3, product=p6)
o4 = OrderInfo(customer=c3, total_price=Decimal('99.80'))
OrderItem(order=o4, product=p4, quantity=10)
o5 = OrderInfo(customer=c4, total_price=Decimal('722.00'))
OrderItem(order=o5, product=p1)
OrderItem(order=o5, product=p2)
commit()
populate_database()
#查询
@db_session
def query():
print(select(p for p in Product if p.id==3)[:])
#多条数据会报错:pony.orm.core.MultipleObjectsFoundError: Multiple objects were found. Use Customer.select(...) to retrieve them
#通过pk获取
print(Product[1].name)
print(Customer.get(id=1).name)
print(Customer.select(lambda c: c.id==1)[:][0].name)
y = 1
print(Product.select_by_sql("SELECT * FROM Product WHERE id=$(y*2)")[0].name)
@db_session
def update():
c1 = Customer.get(id=1)
c1.name="john"
p1 = select(p for p in Product if p.id==3)[:][0]
p1.name="cjavapy"
c2 = Customer.get(id=2)
#更新多个字段
#c.name="cjavapy"
#c.email="cjavapy@gmail.com"
c2.set(name="cjavapy",email="cjavapy@gmail.com")
@db_session
def delete():
p = Product[1]
p.delete()
# 或者:
#delete(p for p in Product if p.id >=5)
# 或:
#使用bulk=True参数是一条delete语句批量删除,否则是先select满足条件数据,然后每次删除一个
Product.select(lambda p: p.id >=5).delete(bulk=True)
query()
update()
delete()