PostgreSQL 的学习及简单的使用示例
准备工作, 下载依赖安装sqlalchemy
使用 sql 语句建表
from sqlalchemy import event
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Table, Column, String, MetaData, create_engine, Integer
# 创建一个数据库链接引擎
engine = create_engine("postgresql+psycopg2://scott:tiger@host/dbname")
# # 创建一个 DBSession
# DB_Session = sessionmaker(bind=engine)
# session = DB_Session()
meta = MetaData(engine)
note_table = Table(
"note", # table name
meta,
Column('name', String, default="*"),
Column('age', Integer)
)
# 建立对应的数据库链接
with engine.connect() as eng :
# 表创建
note_table.create()
# 表插入数据
set_info= note_table.insert().values(title='name', age=23)
# 提交事物
eng.execute(set_info)
# 数据查询
select_statement = note_table.select()
result_set = eng.execute(select_statement)
for r in result_set:
print(r)
# 数据修改
update_statement = note_table.update().where(note_table.c.age=="17").values(title="Some2016Film")
eng.execute(update_statement)
# 数据删除
delete_statement = note_table.delete().where(note_table.c.age == "22")
eng.execute(delete_statement)
使用 orm 操作 sql
from sqlalchemy import create_engine
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建一个数据库链接引擎
engine = create_engine("postgresql+psycopg2://scott:tiger@host/dbname")
# # 创建一个 DBSession
DB_Session = sessionmaker(bind=engine)
session = DB_Session()
DataBase = declarative_base()
class Note(DataBase):
# 设置表名
__tablename__ = 'notes'
title = Column(String, primary_key=True)
text = Column(String)
# 创建表结构并插入新的数据
note_info = Note(title=str(44), text=str('34657'))
session.add(note_info)
session.commit()
# 数据获取
notes = session.query(Note)
for note in notes:
print(note.title)
# 数据修改
note_info.title = "Some2016Film"
session.commit()
# 数据删除
session.delete(note_info)
session.commit()