0

我不明白。我正在尝试使用以下内容在 MS SQL Server 2012 中启动一个全新的表:

In SQL Server:
TABLE [dbo].[Inventory](
[Index_No] [bigint] IDENTITY(1,1) NOT NULL,
[Part_No] [varchar(150)] NOT NULL,
[Shelf] [int] NOT NULL,
[Bin] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Index_No] ASC
)
UNIQUE NONCLUSTERED 
(
    [Part_No] ASC
)
GO

注意:这是一张全新的桌子!里面根本没有数据

接下来,这是 Database.py 文件:

import pymssql
from sqlalchemy import create_engine, Table, MetaData, select, Column, Integer, Float, String, text, 
func, desc, and_, or_, Date, insert

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

USERNAME = "name"
PSSWD = "none_of_your_business"
SERVERNAME = "MYSERVER"
INSTANCENAME = "\SQLSERVER2012"
DB = "Inventory"

engine = create_engine(f"mssql+pymssql://{USERNAME}:{PSSWD}@{SERVERNAME}{INSTANCENAME}/{DB}")

class Inventory(Base):

    __tablename__ = "Inventory"

    Index_No = Column('Index_No', Integer, primary_key=True, autoincrement=True)
    Part_No = Column("Part_No", String, unique=True)
    Shelf = Column("Shelf", Integer)
    Bin = Column("Bin", Integer)

    def __repr__(self):
        return f'Drawing(Index_No={self.Index_No!r},Part_No={self.Part_No!r}, Shelf={self.Shelf!r}, ' \ 
                         f'Bin={self.Bin!r})'


class InventorySchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Inventory
        load_instance = True

还要注意的是,我使用的是 SQLAlchemy 1.4.3,如果有帮助的话。

并在 main.py

import Database as db

db.Base.metadata.create_all(db.engine)

data_list = [{Part_No:123A, Shelf:1, Bin:5},
             {Part_No:456B, Shelf:1, Bin:7},
             {Part_No:789C, Shelf:2, Bin:1}]


with db.Session(db.engine, future=True) as session:
    try:
        session.add_all(data_list) #<--- FAILS HERE AND THROWS AN EXCEPTION
        session.commit()

    except Exception as e:
        session.rollback()
        print(f"Error! {e!r}")
        raise

    finally:
        session.close()

现在我在这个“类'builtins.dict'未映射”上搜索了什么,大多数解决方案都将我带到了我尝试过的marshmallow-sqlalchemy包,但我仍然遇到同样的错误。所以我尝试将 Base.metadata.create_all(engine) 从 Database.py 移动到 main.py。我还尝试在 Inventory 类中实现一个init函数,并调用 Super()。初始化,这不起作用

发生什么了??为什么它会失败,是否有更好的解决方案来解决这个问题?

4

1 回答 1

0

尝试创建 Inventory 对象:

data_list = [
  Inventory(Part_No='123A', Shelf=1, Bin=5),
  Inventory(Part_No='456B', Shelf=1, Bin=7),
  Inventory(Part_No='789C', Shelf=2, Bin=1)
]
于 2021-04-18T04:33:53.027 回答