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(