因此,作为学习 sql alchemy 的一部分,我正在查询 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'>.
我不确定我在哪里出了问题,可能是 sqlalchemy 的版本(我尝试更改它,但它完全抛出了不同的错误)
任何关于我在这里出错的地方的指示将不胜感激。
元数据独立于引擎而存在,因此您无需将它们显式地绑定在一起。 IE。不要将 db 传递给 MetaData()。
一旦完全定义了元数据(和表),您就可以使用引擎来创建元数据,例如
metadata.create_all(engine)
https://docs.sqlalchemy.org/en/20/core/metadata.html#creating-and-dropping-database-tables