我创建了以下课程 这似乎使我可以访问表的架构,但不能访问表本身。我看到的大多数示例,包括手册中的示例,都遵循用于创建表的代码
class DataBase:
def __init__(self,user, password, db, host='localhost', port=5432):
'''Initializes the connection and a metadata objects'''
# We connect with the help of the PostgreSQL URL
# postgresql://federer:grandestslam@localhost:5432/tennis
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, password, host, port, db)
# The return value of create_engine() is our connection object
self.engine = sqlalchemy.create_engine(url, client_encoding='utf8', echo=False) #echo=True enable logging (This is Python loggin module)
self.conn=self.engine.connect()
# We then bind the connection to MetaData()
self.meta = sqlalchemy.MetaData(bind=self.con, reflect=True)
然后我用
if __name__ == '__main__':
db=DataBase('nme','nme','nme')
db.meta.tables['tablename']
但是,这使我可以访问表的架构 我想在创建表后在该表中插入一条记录
编辑:此方法有效,谢谢
known_devices=Table('known_devices',self.meta,autoload=True)
ins=known_devices.insert().values(
....
)
result=self.conn.execute(ins)
答案 0 :(得分:0)
看 https://docs.sqlalchemy.org/en/latest/core/reflection.html和 https://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values
应该是类似
的东西yourtable=Table('tablename', meta, autoload=True)
conn.execute(yourtable.insert(), field="content")