Engine是所有SQLAlchemy应用的入口。Engine通过Pool和Dialect确定连接哪种类型数据库(mysql,sqlserver…)。

create_engine("dialect+driver😕/username:pasword@host:port/database
dialect+driver用于创建一个Dialect对象,host:port用于创建一个Pool对象。
延迟初始化行为
Engine和Pool对象创建后并非直接和DBAPI进行了连接,只有当执行Engine.connect()或Engine.execute()方法后才真正连接。
Engine既可以直接与数据库进行通信(原生SQL模式),也可以将其传递给Session对象以使用ORM(ORM模式)。
当DBURL中存的密码部分存在特殊字符时需要通过编码后将其传入,否则会导致DBURL解析失败。
from sqlalchemy import create_engine
# 演示当密码中包含@和/特殊字符时导致创建Engine对象失败
dburl = "mysql+pymysql://testuser:123@456/!@127.0.0.1:3306/dbtest1"
engine = create_engine(url=dburl,encoding='utf8')
print(engine.connect())

为了解决这个问题,可以先将带有特殊字符的密码部分进行编码,然后将编码后的密码传入url中。
from sqlalchemy import create_engine
import urllib.parse
# 对还有特殊字符的密码进行编码
def encode_pwd(pwd:str) -> str:
encode_password = urllib.parse.quote_plus(pwd)
print(encode_password)
return encode_password
# 生成dburl
def get_dburl(pwd:str) -> str:
password = encode_pwd(pwd)
return f"mysql+pymysql://testuser:{password}@127.0.0.1:3306/dbtest1"
engine = create_engine(url=get_dburl('123@456/!'),encoding='utf8')
print(engine.connect())

这部分参数说明,可查看官方API文档。
# default == 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")
# default == mysqlclient
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")
engine = create_engine("oracle://scott:tiger@127.0.0.1:1521/sidname")
engine = create_engine("oracle+cx_oracle://scott:tiger@tnsname")
# pyodbc == default
engine = create_engine("mssql+pyodbc://scott:tiger@mydsn")
# pymssql
engine = create_engine("mssql+pymssql://scott:tiger@hostname:port/dbname")