我的问题是如何连续获取所有数据(以可打印格式,而不仅仅是对象),用户可以在其中指定所需数据列的名称。这是我目前的代码:
#!/usr/bin/python3
from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
class SQL_Engine:
def __init__(self, dbpath, username, password, dbtype='sqlite', tableName='content_blocks', connector=None):
self.dbpath = dbpath
self.username = username
self.password = password
self.dbtype = dbtype
self.tableName = tableName
self.connector = connector
def Create_Session(self):
if self.connector == None:
engine = create_engine(self.dbtype+"://"+self.username+":"+self.password+"@"+self.dbpath)
else:
engine = create_engine(self.dbtype+"+"+self.connector+"://"+self.username+":"+self.password+"@"+self.dbpath)
Base = declarative_base(engine)
class ContentBlocks(Base):
__tablename__ = self.tableName
__table_args__ = {'autoload':True}
metadata = Base.metadata
Session = sessionmaker(bind=engine)
session = Session()
return session, ContentBlocks, Base
def ViewTable(self):
session, ContentBlocks, Base = self.Create_Session()
request = session.query(ContentBlocks).all()
columns = ContentBlocks.__table__.columns.keys()
table = " ".join(columns)
for entry in request:
for column in columns:
#print entry.column; can't do this as of yet
我在Create_Session()
中看到的初始尝试是检索所有列名并将它们作为变量传递给entry
对象,但这只会导致错误:
Traceback (most recent call last):
File "SQLDeduplication-copy.py", line 131, in <module>
no.ViewTable()
File "SQLDeduplication-copy.py", line 64, in ViewTable
print(entry.column)
AttributeError: 'ContentBlocks' object has no attribute 'column'
因此,我需要将python解释column
作为指针,而不是字面意思。这就是我碰壁的地方,因为我见过的所有其他StackOverflow答案都包括使用列名。
那就是说,如果有人有更好的想法,我对此完全开放。如果有任何错误,请更正我的代码
答案 0 :(得分:0)
IljaEverilä有正确的解决方案。这是:
def ViewTable(self):
session, ContentBlocks, Base = self.Create_Session()
request = session.query(ContentBlocks).all()
columns = ContentBlocks.__table__.columns.keys()
num = 1
for entry in request:
print(num, '\', end=' ')
for column in columns:
print(column, ':', getattr(entry, column), '|', end=' ')