为什么有2个不同的输出

时间:2019-04-19 07:59:35

标签: python sql sqlalchemy

from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey,create_engine
engine = create_engine('sqlite:///college.db',echo = True)
metadata = MetaData()
users = Table('users', metadata,
      Column('id', Integer, primary_key=True),
      Column('name', String(50)),
      Column('fullname', String(50)),
)

addresses = Table('addresses', metadata,
   Column('id', Integer, primary_key=True),
   Column('user_id', None, ForeignKey('users.id')),
   Column('email_address', String(50), nullable=False))
metadata.create_all(engine)

这是第一个输出:

CREATE TABLE addresses (
id INTEGER NOT NULL,
user_id INTEGER,
email_address VARCHAR NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES users (id)

然后,我再次点击运行,输出更改:

2019-04-18 21:06:57,881 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2019-04-18 21:06:57,886 INFO sqlalchemy.engine.base.Engine ()
2019-04-18 21:06:57,892 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2019-04-18 21:06:57,899 INFO sqlalchemy.engine.base.Engine ()
2019-04-18 21:06:57,904 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2019-04-18 21:06:57,909 INFO sqlalchemy.engine.base.Engine ()
2019-04-18 21:06:57,923 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("addresses")
2019-04-18 21:06:57,928 INFO sqlalchemy.engine.base.Engine ()
metadata.create_all(engine)
2019-04-18 21:07:17,156 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2019-04-18 21:07:17,157 INFO sqlalchemy.engine.base.Engine ()

安妮妮妮能否解释为什么我第二次点击运行后会有一些变化?

1 个答案:

答案 0 :(得分:0)

第二次运行代码时,表已经创建,这就是为什么要获得看到的输出的原因。如果要再次获得相同的输出,则必须先删除表:

from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey,create_engine
engine = create_engine('sqlite:///college.db',echo = True)
metadata = MetaData()
users = Table('users', metadata,
      Column('id', Integer, primary_key=True),
      Column('name', String(50)),
      Column('fullname', String(50)),
)

addresses = Table('addresses', metadata,
   Column('id', Integer, primary_key=True),
   Column('user_id', None, ForeignKey('users.id')),
   Column('email_address', String(50), nullable=False))
metadata.create_all(engine)
users.drop(engine)
addresses.drop(engine)

但是,那当然会让您有一个空数据库! 要在重新创建表时获取异常,可以使用checkfirst参数:

metadata.create_all(engine, checkfirst=False)

您看到的PRAGMA输出对于获取表的某些元数据很有用:

foo = engine.execute('PRAGMA table_info("addresses")').fetchall()
print(foo)

另请参阅this question