我正在将Python Sqlalchemy用于MYSQL数据库。我编写了以下脚本来创建类对象,然后在表中添加了一些行。
from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey
from sqlalchemy.dialects.mysql.base import VARCHAR, LONGTEXT, INTEGER
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("mysql+mysqldb://root:@localhost/mydb")
connection = engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
metadata = MetaData()
class User(Base):
__tablename__ = 'User'
id = Column('id', INTEGER(display_width=11), primary_key=True, nullable=False)
email = Column('email', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100), unique=True)
password = Column('password', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=45))
name = Column('name', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100))
现在,我需要从“用户”表中获取所有行,所以我要这样做:
user = session.query(User).all()
print(user)
但是我得到的输出不是表数据,而是这个:
[<__main__.User object at 0x7f10b0c6ebe0>, <__main__.User object at 0x7f10b0c6ec50>]
如何从表格中获取实际数据?任何帮助将不胜感激
答案 0 :(得分:1)
您将获得的输出是记录的元组。 因此,使用循环
users = session.query(User).all()
for user in users:
print (user)
print (user.id, user.email, user.password, user.name)
答案 1 :(得分:0)
您应该在User类中编写__str__方法,例如:
class User(Base):
...
def __str__(self):
str_out = 'id={} email={} password={} name={}'
str_formated = str_out.format(self.id,self.email,self.password,self.name)
return str_formated