2014-03-25 84 views
0
from sqlalchemy import Column, Integer, String, MetaData, Table, create_engine 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import sessionmaker 

#table columns describing 
params = dict(lid  = Column(Integer, primary_key=True), 
       cab_name = Column(String)) 

table_name = dict(__tablename__ = "table") 


def cab_init(self, **kwargs): 
    for k,v in kwargs.items(): 
     setattr(self, k, v) 

methods = dict(__init__ = cab_init) 

cab_item = type("cab_item", (declarative_base(),), dict (methods.items() 
              + params.items() 
              + table_name.items())) 


engine = create_engine('sqlite:///:memory:', echo=False) 
meta = MetaData() 

table = Table('table', meta,        #(*1) 
      Column('lid', Integer,primary_key=True), 
      Column('cab_name', String), 
      ) 
#table = Table(name = 'table', metadata = meta, args = params.values()) #(*2) 
meta.create_all(engine) 

session = sessionmaker(engine)() 
session.merge(cab_item(lid=10, cab_name="blah")) 

session.commit() 

(* 1)的作品就好了,(* 2)產生一個錯誤表構造工程奇怪

sqlalchemy.exc.OperationalError: (OperationalError) no such table: table u'SELECT "table".lid AS table_lid, "table".cab_name AS table_cab_name \nFROM "table" \nWHERE "table".lid = ?' (10,)

爲什麼?

回答

1

我找到了解決辦法

  1. params爲申報錯誤的。正確的做法是

    params2 = (Column('lid', Integer, primary_key=True), Column('cab_name',String))

  2. 呼叫Table男星像table = Table('table', meta, *params2)