SQLAlchemy
声明
写这篇文章的目的只是为了自己在遇到问题时方便查找,文中会有SqlAlchemy官方文档中的内容。
sqlalchemy是一个对象关系映射器, 提供了一种将用户定义的Python类与数据库表以及这些类(对象)的实例与相应表中的行关联起来的方法。ORM即Object - Relation - Mapping
创建连接
使用SQLAlchemy的第一步是创建一个数据库连接,这里使用的是mysql数据库
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://username:password@ip/dbname')
这个 create_engine()
函数生成 Engine
基于URL的对象。以下是这些URL RFC-1738 ,通常可以包括用户名、密码、主机名、数据库名称以及用于附加配置的可选关键字参数。在某些情况下,文件路径被接受,而在其他情况下,“数据源名称”将替换“主机”和“数据库”部分。数据库URL的典型形式是:
dialect+driver://username:password@host:port/database
PostgreSQL
# default
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
# default
engine = create_engine('mysql://scott:tiger@localhost/foo')
# mysqlclient (a maintained fork of MySQL-Python)
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
# PyMySQL
engine = create_engine('mysql+pymysql://scott:tiger@localhost/foo')
Oracle
engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
engine =