2012-09-23 32 views
0

我试图插入一行有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 
+0

提示:当你进入MySQL shell并输入'SHOW CREATE TABLE Stock'时它会显示'AUTO_INCREMENT'?会发生什么? –

+0

@BurhanKhalid,是的。 – tuxuday

回答

0

添加autoincrement=True到您的列。

+0

已经尝试过,但无济于事。 – tuxuday

+0

它不在你的代码中;也许你应该发布你正在使用的完整代码。 –

+0

认为'autoincrement'是可选的,我没有在原来的代码,但尝试了谷歌搜索后。用更多的代码更新。 – tuxuday

0

明白了。转换为Integer后,我的列类型为String,工作正常。

相关问题