0

I am new to SQLAlchemy. I created a basic table using the Metadata() and closed the connection. Now I cannot seem to access the database even when I reopen the connection. I seem to be missing a line of code but cannot figure out what it is.

This is how I try to reopen the connection:

engine = create_engine('sqlite:///C:\\Users\\..\\Documents\\Untitled Folder\\Database.db', echo= False) 
metadata = MetaData()
conn = engine.connect()
trans = conn.begin()
trans

However every time I try to select or do something to my table contained in the database I get the following error:

>>>ins = tabledata.insert().values(fullname= 'Hello', year='2018')

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-a148c71d348c> in <module>()
----> 1 ins = tabledata.insert().values(fullname= 'Hello', year='2018')

NameError: name 'tabledata' is not defined

I know the table exists and hasn't been deleted as I have a browser which lets me look at the database and it is still there.

For reference this is how I created my table in the database: Everything worked fine until I closed the connection and tried to restart it again.

metadata = MetaData()

tabledata = Table('tabledata', metadata,
    Column('id', Integer, primary_key= True ),
    Column('fullname', String),
    Column('year', String),)

metadata.create_all(engine)

Any idea as to what I need to do to be able to access the Table again?

4

1 回答 1

0

为将来可能会问同样问题的其他人找到了缺失的线路!

tabledata = Table('tabledata', metadata, autoload=True, autoload_with=engine)

所以重新加载表的完整方法是:

engine = create_engine('sqlite:///C:\\Users\\..\\Documents\\UntitledFolder\\Database.db', echo= False) 
metadata = MetaData()
tabledata = Table('tabledata', metadata, autoload=True, autoload_with=engine)
conn = engine.connect()
conn

这一切都有效!

于 2018-09-07T10:08:47.830 回答