SQLAlchemy报错:期望传入字符串却得到Engine对象,求解决
问题排查:SQLAlchemy初始化MetaData报错
我正在学习SQLAlchemy,查询Chinook数据库,按照文档和课程结构编写了查询表的代码:
### --- USING SQL ALCHEMY TO QUERY DATABASES --- ### ### --- IMPORT --- ### from sqlalchemy import ( create_engine, Table, Column, Float, ForeignKey, Integer, String, MetaData ) ### --- SETUP DB --- ### # executing the instructions from our localhost "chinook" db #(3/// means hosted locally) db = create_engine("postgresql:///chinook") # save a collection about our table objects and the data inside them meta = MetaData(db) ### --- QUERY --- ### #1. create variable for table we want to utilize #(we feed in the subheadings we want, artist, id, name) artist_table = Table( "Artist", meta, Column("ArtistId", Integer, primary_key=True), Column("Name", String) ) #variable for album other tables would be made in the same way album_table = Table( "Album", meta, Column("AlbumId", Integer, primary_key=True), Column("Title", String), Column("ArtistId", Integer, ForeignKey("artist_table.ArtistId")) ) #seeing as artist id is a key that's linked from artist this is a foreign key for this table #pretty much we want to set the table and column to point to track_table = Table( "Track", meta, Column("TrackId", Integer, primary_key=True), Column("Name", String), Column("AlbumId", Integer, ForeignKey("album_table.AlbumId")), Column("MediaTypeId", Integer, primary_key=False), Column("GenreId", Integer, primary_key=False), Column("Composer", String), Column("Milliseconds", Integer), Column("Bytes", Integer), Column("UnitPrice", Float) )
运行时出现如下报错:
Traceback (most recent call last): File "/workspace/PostGres_Chinook_Example/sql-expressions.py", line 15, in <module> meta = MetaData(db) ^^^^^^^^^^^^ File "/workspace/.pip-modules/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 5481, in __init__ raise exc.ArgumentError( sqlalchemy.exc.ArgumentError: expected schema argument to be a string, got <class 'sqlalchemy.engine.base.Engine'>.
排查与修复方向
修正MetaData初始化参数
SQLAlchemy 2.0+版本中,MetaData的第一个参数是schema名称(字符串类型),若要绑定数据库引擎,需使用bind参数。把原代码中的:meta = MetaData(db)修改为以下两种写法之一:
# 写法1:通过bind参数绑定引擎 meta = MetaData(bind=db) # 写法2:先初始化再绑定 meta = MetaData() meta.bind = db修复ForeignKey引用错误
代码中ForeignKey("artist_table.ArtistId")的写法错误,ForeignKey需要引用数据库中实际的表名和列名,而非Python变量名。正确写法应为:# Album表的ForeignKey修正 Column("ArtistId", Integer, ForeignKey("Artist.ArtistId")) # Track表的ForeignKey修正 Column("AlbumId", Integer, ForeignKey("Album.AlbumId"))版本兼容问题处理
更换版本后出现其他错误,说明课程/文档使用的SQLAlchemy版本与你当前安装的版本存在API差异。建议:- 确认课程使用的SQLAlchemy版本号
- 通过
pip install sqlalchemy==<具体版本号>安装对应版本,避免跨版本API不兼容问题
内容的提问来源于stack exchange,提问作者user21629409
相关产品推荐
相关产品推荐

