My question is how does one get all data in a row (in a printable format, not just the object) where the user can specify the names of the columns of data they want. Here's my current code:
#!/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
My initial attempt, as you can see in Create_Session()
was to retrieve all the column names and pass them as a variable into entry
object, however this just results in an error:
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'
Thus, I need to make python interpret column
as a pointer, not literally. And this is where I hit a wall because all the other StackOverflow answers I've seen include using the column name.
That said, if anyone has a better idea, I am completely open to that. Please correct my code if there are any mistakes in it