SQLAlchemy ORM – Object Relational Tutorial
参考:
http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html
查看版本
>>> import sqlalchemy
>>> sqlalchemy.__version__
'1.0.9'
创建连接
from sqlclachemy import create_engine
engine = create_engine("sqlite:///:memory:", echo=True)
‘sqlite:///:memory:’ 是 database URL
postgresql
sqlalchemy 默认使用 psycopg2
# 默认情况(即使用psycopg2)
engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')
# 使用psycopg2
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')
# 使用pg8000
engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')
MySQL
默认使用mysql-python
# 默认情况(即使用mysql-python)
engine = create_engine('mysql://scott:tiger@localhost/foo')
# 使用mysql-python
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
# 使用MySQL-connector-python
engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')
# 使用OurSQL
engine = create_engine('mysql+oursql://scott:tiger@localhost/foo')
Oracle
默认使用cx_oracle
# 默认情况(即使用cx_oracle)
engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
# 使用cx_oracle
engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')
Microsoft SQL Server
默认使用pyodbc
# 使用pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')
# 使用pymssql
engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')
SQLite
因为sqlite是基于文件的数据库,所以database URL 和前面的不太一样。
# database URL 形式是 sqlite://<nohostname>/<path>
engine = create_engine('sqlite:///foo.db')
# 在Unix/Mac
engine = create_engine('sqlite:////absolute/path/to/foo.db

这篇博客介绍了SQLAlchemy ORM的使用,包括如何创建连接到不同类型的数据库(如postgresql、MySQL等)、建立表、进行基本的CRUD操作。创建 declarative base class 和 User 表,以及如何利用session进行数据插入、更新、读取和删除。示例涵盖了query操作、过滤、别名使用和count、update、delete等操作。
&spm=1001.2101.3001.5002&articleId=50197197&d=1&t=3&u=25b9f970283e40d7b64d724c79ab097f)
1434

被折叠的 条评论
为什么被折叠?



