在不知道sqlalchemy中的列名的情况下获取整行的数据

2024-10-01 17:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是如何获得一行中的所有数据(以可打印的格式,而不仅仅是对象),用户可以在其中指定所需数据列的名称。以下是我当前的代码:

#!/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对象中,但是这只会导致错误:

^{pr2}$

因此,我需要让python将column解释为一个指针,而不是逐字解释。这就是我遇到麻烦的地方,因为我看到的所有其他StackOverflow答案都使用了列名。在

也就是说,如果有人有更好的主意,我完全愿意接受。如果我的代码有错误,请改正


Tags: fromimportselfconnectorbasesqlalchemysessioncreate
1条回答
网友
1楼 · 发布于 2024-10-01 17:24:08

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=' ')

相关问题 更多 >

    热门问题