python - SQLAlchemy 反射 : How do I query data from specific columns?

标签 python mysql sqlalchemy

使用SQLAlchemy反射,如何查询特定列的数据?

testtable = Table('member', Metadata, autoload=True)

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable).filter_by(is_active=1, is_deleted=0): 
        print(loopCounter + 1, data)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

TestConnection()

上面的查询为我提供了成员 表中所有列中的所有数据。然而,我想要的是从列中获取特定数据。例如。我想检索 usernamepassword 列,但语法不正确。以下是我目前所拥有的:

def TestConnection():
    loopCounter = 0 
    for password, username in session.query(testtable).filter_by(is_active=1, is_deleted=0):
        print(loopCounter + 1, data)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

失败并出现错误:

Traceback (most recent call last):
File "/home/workspace/upark/src/monitor.py", line 36, in <module>
TestConnection()
File "/home/workspace/upark/src/monitor.py", line 26, in TestConnection
for password, username in session.query(testtable).filter_by(is_active=1, is_deleted=0):
ValueError: too many values to unpack (expected 2)

我正在使用来自 Oracle 的 Python3.2、SQLAchemy0.8 和 mysqlconnector。

编辑:一些小的进步

刚刚发现我可以在返回所有结果后“过滤”出列,如下所示:

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable).filter_by(is_active=1, is_deleted=0): 
        print(loopCounter + 1, data.password, data.username)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

这将给出:

1 pass1 userone
2 pass2 usertwo

但如您所见,那是在我取回所有列之后。我想要的是只从我需要的列中获取数据。例如。 Members 表有 10 列。为了提高效率,我只需要从其中两个获取数据。

最佳答案

只需指定要选择的列 [session.query(testtable.c.password, testtable.c.username)] 而不是整个表 [session.query(testtable)]:

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable.c.password, testtable.c.username).filter_by(is_active=1, is_deleted=0): 
        pwd, usr = data
        print(loopCounter + 1, pwd, usr)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

关于python - SQLAlchemy 反射 : How do I query data from specific columns?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15223722/

相关文章:

python - 如何使用 Pandas 在 MySQL-DB 中加载和保存部分表

python - SQLAlchemy 添加与 add_all

python - 如何将字符串保存到字符列表中,但也能够以相反的顺序打印出该列表

python - 如何使用python向MySQL表中添加记录?

python - 设置QBoxLayout最大尺寸?

php - 在数据库中查找、获取和替换部分字符串的最快方法

sqlalchemy - 给定一个声明性 SQLAlchemy 类,我如何以编程方式检索其作为主键的 Column 对象的列表?

Python 单元测试 : type checking custom class type

python - 在 Python 文件对象上使用迭代器时是否需要 close()

python - gunicorn 中 worker 和 worker_connections 的区别?