我试图插入一行有auto_increament
以及一些外键的表。所有的外键都存在。但它会引发错误。通过sqlalchemy插入记录到mysql表中,使用autoinc引发错误
sqlalchemy.orm.exc.FlushError: Instance Stock at 0x9cf062c has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values. Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.
即使插入记录通过mysql,通过复制粘贴sql生成echo=True
,正在执行。
股票类
class Stock(Base):
__tablename__ = 'Stock'
Code = Column('Code',String(8),primary_key=True)
Symbol = Column('Symbol',String(128))
ListingName = Column('ListingName',String(256))
ListingDate = Column('ListingDate',DateTime())
RecordAddedDate = Column('RecordAddedDate',DateTime())
HomeCountry = Column('HomeCountry',ForeignKey('Country.Code'))
PrimaryExchange = Column('PrimaryExchange',ForeignKey('Exchange.Code'))
BaseCurrency = Column('BaseCurrency',ForeignKey('Currency.Code'))
InstrumentType = Column('InstrumentType',ForeignKey('Instrument.InstrumentType'))
记录插入
Engine = sqlalchemy.create_engine('mysql://user:[email protected]/db',echo=True)
Session = sqlalchemy.orm.sessionmaker(bind=Engine)
SessionObj = Session()
NewStock = Stock()
NewStock.InstrumentType = 'Stock'
NewStock.Symbol = 'MSFT'
NewStock.ListingName = 'Microsoft'
NewStock.HomeCountry = 'IN'
NewStock.PrimaryExchange = 'NSEOI'
NewStock.BaseCurrency = 'INR'
NewStock.ListingDate = datetime.datetime.now().strftime("%Y%m%d")
NewStock.RecordAddedDate = datetime.datetime.now().strftime("%Y%m%d")
print NewStock
SessionObj.add(NewStock)
SessionObj.flush()
print NewStock.Code
提示:当你进入MySQL shell并输入'SHOW CREATE TABLE Stock'时它会显示'AUTO_INCREMENT'?会发生什么? –
@BurhanKhalid,是的。 – tuxuday