代码之家  ›  专栏  ›  技术社区  ›  ShaAnder

为什么sqllachemy返回的是类而不是字符串

  •  0
  • ShaAnder  · 技术社区  · 5 月前

    因此,作为学习sql炼金术的一部分,我正在查询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的版本(我试图更改它,但它抛出了一个完全不同的错误)之外,我不确定我在哪里出了问题

    如果您能告诉我这里哪里出了问题,我们将不胜感激。

    1 回复  |  直到 5 月前
        1
  •  0
  •   Ian Wilson    5 月前

    元数据独立于引擎存在,因此您不必显式地将它们联系在一起。即,不要将db传递给元数据()。

    一旦你完全定义了元数据(和表),你就可以使用引擎创建元数据,如下所示

    metadata.create_all(engine)

    https://docs.sqlalchemy.org/en/20/core/metadata.html#creating-and-dropping-database-tables